Generate a new canvas for every new keypress (shooting gun turret) - python

First, I am a beginner with kivy, and not very experienced in Python either.
The following program is strictly meant to educate myself in kivy basics, nothing more.
The program is a game where the user controls a gun turret. He shots at objects that bounce around in the program window, while points and time used are shown in the bar below. (Currently occupied by a button.) The keys that turn the turret are "A" and "D", while "P" is for shooting.
The problem I am currently having is this:
I need to generate additional projectile graphics every time the user press "P". At a later stage I will also need to generate and remove target objects graphics when they get hit by a shot, which I guess will involve the same technique.
How should I go about to generate additional canvas´ and\or ellipse objects? (the graphical representation of each shot)
My Python code:
from kivy.config import Config
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '900')
Config.set('graphics','resizable',0)
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty
from kivy.properties import ReferenceListProperty
from kivy.properties import BooleanProperty
from kivy.properties import ListProperty
from kivy.clock import Clock
import math
from kivy.core.window import Window
class MainScreen(BoxLayout): #Contains the whole program
#Turret rotation:
the_angle = NumericProperty(0)
#Projectile vector:
the_pos_x = NumericProperty(0)
the_pos_y = NumericProperty(0)
the_pos = ReferenceListProperty(the_pos_x, the_pos_y)
#Shots data:
shot_fired = BooleanProperty(False)
shot_count = NumericProperty(0)
angle_list = ListProperty([])
pos_list_x = ListProperty([])
pos_list_y = ListProperty([])
def update(self, dt):
if self.shot_fired == True:
self.shot_count += 1
self.angle_list.append(self.the_angle)
self.pos_list_x.append(400)
self.pos_list_y.append(400)
self.shot_fired = False
for i in range(0, self.shot_count):
self.shoot(i, self.angle_list[i], self.pos_list_x[i], self.pos_list_y[i])
def shoot(self, cur_shot, the_angle, pos_x, pos_y):
#Make correct shot data:
velocity = 1.5
angle_rad = math.radians(the_angle+90)
pos_x += ( math.cos(angle_rad)*velocity )
pos_y += ( math.sin(angle_rad)*velocity )
#Give the shots positions new data :
self.the_pos_x = pos_x
self.the_pos_y = pos_y
#Update data for the next round of this function:
self.pos_list_x[cur_shot] = pos_x
self.pos_list_y[cur_shot] = pos_y
def keypress(self, *args):
the_key = args[3]
if the_key == "a":
self.the_angle += 1.5
elif the_key == "d":
self.the_angle += -1.5
elif the_key == "p":
self.shot_fired = True
class GameScreen(RelativeLayout): #The game part of the screen
pass
class Gun(Widget): #Holds canvas and drawings for gun
pass
class Projectile(Widget): #Holds canvas and drawings for projectile
pass
class InfoBar(FloatLayout): #Holds point counters and buttons
pass
#Set screen size and prevent resizing:
Window.size = (800, 900)
class MyApp(App):
def build(self):
Builder.load_file("interface.kv")
game = MainScreen()
Window.bind(on_key_down=game.keypress)
Clock.schedule_interval(game.update, 1.0/60.0)
return game
MyApp().run()
My kv code:
<MainScreen>:
the_angle: 45
the_pos: [400,400]
GameScreen:
size_hint:(None,None)
size:800,800
pos_hint:{"top":1, "left":1}
Gun:
canvas.before:
PushMatrix
Rotate:
axis: 0,0,1
angle: root.the_angle
origin: 400,400
canvas:
Rectangle:
size:50,100
pos: 400,400
canvas.after:
PopMatrix
Projectile:
canvas:
Ellipse:
size:10,20
pos: root.the_pos[0], root.the_pos[1]
InfoBar:
size_hint:(None,None)
size:800,100
pos_hint:{"bottom":1, "left":1}
Button:

Related

How to control Atlas images in memory with CoreImage, Python and Kivy

So i'm making this arcade game and i have a state machine that takes an object(the enemy class) as a constructor parameter, and i have 1 folder for the enemy sprite.
So when i instantiate 1 state machine the game works fine, but when i instantiate 2 state machines(2 enemies) things get weird, when 1 enemy gets to the end of the screen and turn around with kivy's "flip_horizontal" the other enemy turns around too, and its because both state machines are controlling the same enemy folder(same images).
Now if i create an enemy folder for each state machine then it works fine but this is not good. so i thought about manipulating the images in memory, this way the effects of a state machine on the images wont be shared to other state machines.
I tried to do this using CoreImage but the furthest i got was to get a static on the screen and move the "x position", no animation, nothing.
So would anyone help me with this? or if you have a better solution i will be grateful.
heres a sample code:
statemachine.py:
from kivy.app import App
from kivy.properties import Clock, StringProperty, NumericProperty
from kivy.atlas import Atlas
from kivy.uix.image import Image
from itertools import cycle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.core.window import Window
class EnemyFSM(FloatLayout):
def __init__(self, enemy_object, **kwargs):
super().__init__(**kwargs)
self.enemy = enemy_object
self.states = {'ROAM': 'ROAM',
'CHASE': 'CHASE',
'ATTACK': 'ATTACK',
'DEAD': 'DEAD',
'IDLE': 'IDLE'}
self.state = self.states['ROAM']
self.init_state = True
def update(self, dt):
if self.state == 'ROAM':
self.roam_state()
def idle_state(self):
self.enemy.methods_caller("walk")
def roam_state(self):
self.enemy.methods_caller("walk")
main.py:
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.floatlayout import MDFloatLayout
from kivy.properties import Clock
from kivy.uix.image import Image
from kivy.properties import NumericProperty
from random import uniform as rdm
from random import randint as rdi
from random import choice
enemy_list = []
from baseenemy import Enemy
from statemachine import EnemyFSM
class LevelOne(MDScreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Clock.schedule_once(self.setup, 1/60)
def setup(self, dt):
self.left_side_spawn = rdi(-500, -100)
self.right_side_spawn = rdi(500, 600)
self.spawn_side = [self.left_side_spawn, self.right_side_spawn]
self.speed = rdi(1, 5)
"""here we instatiate the enemies, 1 works fine, 2 or more then hell breaks loose unless we give each state machine its own image folder"""
for _ in range(1):
self.base_enemy = Enemy(choice(self.spawn_side), rdm(1, 5))
self.add_widget(self.base_enemy)
self.enemy_ai = EnemyFSM(self.base_enemy)
self.add_widget(self.enemy_ai)
enemy_list.append(self.enemy_ai)
Clock.schedule_interval(self.init_game, 1/60)
def init_game(self, dt):
for i in range(len(enemy_list)):
enemy_list[i].update(dt)
class MainApp(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Red"
return None
def on_start(self):
self.fps_monitor_start()
main.kv:
LevelOne:
<EnemyFSM>:
<Enemy>:
source: root.frame_path #the frame_path variable in the enenmy class
size_hint: None, None
size: "150dp", "150dp"
x: root.xpos
y: root.ypos
baseenemy.py:
from kivy.app import App
from kivy.atlas import Atlas
from kivy.properties import Clock, StringProperty, NumericProperty
from kivy.uix.image import Image
from kivy.core.image import Image as CoreImage
import itertools
"""Method to set up the frame names"""
def frame_setup(src):
return [f"1_enemies_1_{src}_{i}" for i in range(20)]
"""Path to the image folder with the atlas"""
def create_frame_path(frame_name):
return {'my_source':
f"atlas://{frame_name}/{frame_name}_atlas/1_enemies_1_{frame_name}_0",
'my_atlas': f"atlas://{frame_name}/{frame_name}_atlas/"}
class Enemy(Image):
xpos = NumericProperty(10)
ypos = NumericProperty(50)
init_frame = create_frame_path('walk')#default frame state 'walk'
frame_path = StringProperty(init_frame['my_source'])#path to the image, this var is also the images source in the .kv file
frame_atlas_path = None
updated_frames = []
previous_frame = None
frame_cycle_called = False
updated_frames_cycle = None
fliped = 0
def __init__(self, spawn_pos, speed, *args, **kwargs):
super().__init__(**kwargs)
self.goal = 0
self.methods_dict = {'walk': self.walk}
self.methods_call = None
self.step = 3
self.xpos = spawn_pos
"""this method, takes a param, and sets up everything
the new frame if the frame is diferent than the current frames'walk'
creates the frame list..."""
def methods_caller(self, new_src):
#The src param is the state of the enemy
#which will tell which frames to set up
#now its just "walk"
self.src = new_src
self.updated_frames = frame_setup(self.src)
#if a state change has occured these lines will run and set up
# a new set of frames according to the new state but for now its just the 'walk' state
if self.previous_frame is not new_src:
self.previous_frame = new_src
self.methods_call = self.methods_dict[new_src]#this get the dict element which is a function and assign to the var
self.frame_path = str(create_frame_path(new_src))
self.frame_atlas_path = create_frame_path(new_src)
self.frame_cycle_called = False
if not self.frame_cycle_called:
self.updated_frames_cycle = itertools.cycle(self.updated_frames)
self.frame_cycle_called = True
self.methods_call()#calling the method we got from the dict element which call the walk method
def walk(self):
#this is where the walking animation happen
if self.xpos >= 700:
self.goal = 1
if self.xpos <= -300:
self.goal = 0
self.frame_path =
self.frame_atlas_path['my_atlas']+next(self.updated_frames_cycle)
image_side = Image(source=self.frame_path).texture
if self.goal == 0 and int(round(image_side.tex_coords[0])) != 0:
image_side.flip_horizontal()
self.fliped = 0
if self.goal == 1 and int(round(image_side.tex_coords[0])) != 1:
image_side.flip_horizontal()
self.fliped = 1
if self.fliped == 0:
self.xpos += self.step
if self.fliped == 1:
self.xpos -= self.step
And finally heres the link to a zip file with the image folder:
https://drive.google.com/file/d/11eGTS_pI690eI5EhxAAoRmT05uNW3VOM/view?usp=sharing
and sorry for the long text.

How can I successfully create an infinitely scrolling background?

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Rectangle
from kivy.core.image import Image as CoreImage
from kivy.core.window import Window
class Background(Widget):
def __init__(self, **kw):
super(Background, self).__init__(**kw)
with self.canvas:
texture = CoreImage('space.png').texture
texture.wrap = 'repeat'
self.rect_1 = Rectangle(texture=texture, size=self.size, pos=self.pos)
Clock.schedule_interval(self.txupdate, 0)
def txupdate(self, *l):
t = Clock.get_boottime()
self.rect_1.tex_coords = -(t * 0.001), 0, -(t * 0.001 + 10), 0, -(t * 0.001 + 10), -10, -(t * 0.001), -10
class CosmicPolygons(App):
def build(self):
return Background(size=Window.size)
if __name__ == "__main__":
CosmicPolygons().run()
I've tried many different ways and attempts in order to create a scrolling background in Kivy. This was the best method I could find as it was the only one that didn't crash. But I'm pretty sure it's still outdated as it did not work as intended, in addition to distorting my png greatly.
If anyone has any ideas on how to achieve this, let me know. Thanks in advance.
Image of current app:
Space.png:
Here is another approach that just creates a list of Images and moves them across the screen:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.core.window import Window
class BgImage(Image):
pass
Builder.load_string('''
<BgImage>:
source: 'stars.png'
allow_stretch: True
size_hint: None, 1
width: self.image_ratio * self.height
''')
class Background(FloatLayout):
def __init__(self, **kwargs):
super(Background, self).__init__(**kwargs)
self.deltax = 3 # sets speed of background movement
self.bg_images = [] # list of Images that form the background
Clock.schedule_once(self.set_up_bg)
def set_up_bg(self, dt):
# create BgImages and position them to fill the Background
self.start_x = None
pos_x = -1
while pos_x < self.width:
img = BgImage()
if self.start_x is None:
# starting position of first Image is just off screen
self.start_x = -self.height * img.image_ratio
pos_x = self.start_x
img.pos = (pos_x, 0)
self.bg_images.append(img)
self.add_widget(img)
# calculate starting position of next Image by adding its width
pos_x += self.height * img.image_ratio
# start moving the background
Clock.schedule_interval(self.update, 1.0/30.0)
def update(self, dt):
for img in self.bg_images:
img.x += self.deltax
if img.x > self.width:
# this Image is off screen, move it back to starting position
img.x = self.start_x
class CosmicPolygons(App):
def build(self):
return Background(size=Window.size)
if __name__ == "__main__":
CosmicPolygons().run()

Kivy performance degradation over time

I am learning Kivy, and to make it more fun I am creating a small 2D game. For now its just a tank that can be controlled with WASD and shot projectiles with o.
The problem is that the FPS degrades over time. This happens even if I do nothing in the game. I don´t have an FPS counter, but its something like half the FPS after a minute of gametime.
My feeling is that the problem lies somewhere in the updating of canvas in widgets. Since the slowdowns occour even if the player does nothing for the whole game, its seems like there is data somewhere that is just added and added. I don´t know how to better explain it, other than its weird ...
A quick overview of how the game is programmed so far:
The main widget is the class Game. It detects keypresses and runs "Clock.schedule_interval-function".
The Tank widget is a child of Game. It holds some data and loads the hull and turret sprites via Kivys Image widget, which becomes its child. It has its own update function that updates everything tank-related, including setting the position of its canvas and rotating the hull and turret image canvas. The update-function in the Tank widget class is inwoked by "Clock.schedule_interval" in Game class.
The Shots widget does the same as the Tank widget, only it holds data for each shot fired instead
"Clock schedule_interval"-function holds a list of each shot widget, and deletes them when they get off screen. However, the slowdown problems persist even if no shots are fired.
I have attached the complete code. This might be excessive, but I don´t know wich part of it that provokes slowdowns. If you want to run the game, just put those four python-files in the same folder, and the images in a sub-folder called "images tank".
I hope someone can take a look at it :)
main.py:
#Import my own modules:
import tank
import shot
from stats import Stats
#Import kivy:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
#Set window size properties:
from kivy.config import Config
Config.set('graphics','resizable',0)
from kivy.core.window import Window
class Game(Widget):
def __init__(self):
#General settings:
super(Game, self).__init__()
Clock.schedule_interval(self.update, 1.0/60.0)
#Add keyboard:
self._keyboard = Window.request_keyboard (callback=None, target=self, input_type="text")
#Bind the keyboard to a function:
self._keyboard.bind(on_key_down=self.keypress)
self._keyboard.bind(on_key_up=self.keyUp)
#P1 tank starting values:
self.keypress_p1 = {"forward":False, "backward":False, "left":False, "right":False, "turret_left":False, "turret_right":False, "fire":False}
#P1 tank widget:
self.tank_p1 = tank.Tank()
self.add_widget(self.tank_p1)
#P1 shots list:
self.shotsList_p1 = []
#Keyboard press detection:
def keypress(self, *args):
key = args[2]
if key == "w":
self.keypress_p1["forward"]=True
if key == "s":
self.keypress_p1["backward"]=True
if key == "a":
self.keypress_p1["left"]=True
if key == "d":
self.keypress_p1["right"]=True
if key == "q":
self.keypress_p1["turret_left"]=True
if key == "e":
self.keypress_p1["turret_right"]=True
if key == "o":
self.keypress_p1["fire"]=True
#Keyboard button up detection:
def keyUp(self, *args):
key = args[1][1]
if key == "w":
self.keypress_p1["forward"]=False
if key == "s":
self.keypress_p1["backward"]=False
if key == "a":
self.keypress_p1["left"]=False
if key == "d":
self.keypress_p1["right"]=False
if key == "q":
self.keypress_p1["turret_left"]=False
if key == "e":
self.keypress_p1["turret_right"]=False
if key == "o":
self.keypress_p1["fire"]=False
#Parent update function that the clock runs:
def update(self, dt):
#Add new shots:
if self.keypress_p1["fire"]:
self.shot = shot.Shots(self.tank_p1.my_pos, self.tank_p1.my_angle+self.tank_p1.my_turretAngle)
self.shotsList_p1.append(self.shot)
self.add_widget(self.shot)
self.keypress_p1["fire"] = False
#P1 tank update:
self.tank_p1.update(self.keypress_p1)
#P1 shot update:
for i in range(len(self.shotsList_p1)-1,-1,-1):
self.shotsList_p1[i].update()
#Remove widgets that are outside the screen:
if ( 0<=self.shotsList_p1[i].my_pos[0]<Stats.winSize[0] and 0<=self.shotsList_p1[i].my_pos[1]<Stats.winSize[1] )==False:
self.remove_widget(self.shotsList_p1[i])
del self.shotsList_p1[i]
class MyApp(App):
def build(self):
game = Game()
Window.size = Stats.winSize
return game
MyApp().run()
tank.py:
#Import own modules:
from stats import Stats
#import python:
import math
#Import Kivy:
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.graphics.context_instructions import PushMatrix, PopMatrix, Rotate, Translate, MatrixInstruction
from kivy.graphics.fbo import Fbo
class Tank(Widget):
def __init__(self):
super(Tank, self).__init__()
#Position and rotation values for the tank:
self.my_pos = [0,0]
self.posChange = [0,0]
self.my_angle = 0
self.angleChange = 0
self.my_turretAngle = 0
self.turretAngleChange = 0
#Hull widget:
self.hull = Hull()
self.add_widget(self.hull)
self.hull.center_x = self.my_pos[0]
self.hull.center_y = self.my_pos[1]
#Turret widget:
self.turret = Turret()
self.add_widget(self.turret)
self.turret.center_x = self.my_pos[0]
self.turret.center_y = self.my_pos[1]
def update(self, keypress):
if keypress["forward"]:
self.my_pos[0] -= Stats.hull_t1["forward"]*math.sin(math.radians(self.my_angle))
self.my_pos[1] += Stats.hull_t1["forward"]*math.cos(math.radians(self.my_angle))
self.posChange[0] = -Stats.hull_t1["forward"]*math.sin(math.radians(self.my_angle))
self.posChange[1] = Stats.hull_t1["forward"]*math.cos(math.radians(self.my_angle))
if keypress["backward"]:
self.my_pos[0] -= Stats.hull_t1["backward"]*math.sin(math.radians(self.my_angle))
self.my_pos[1] += Stats.hull_t1["backward"]*math.cos(math.radians(self.my_angle))
self.posChange[0] = -Stats.hull_t1["backward"]*math.sin(math.radians(self.my_angle))
self.posChange[1] = Stats.hull_t1["backward"]*math.cos(math.radians(self.my_angle))
if keypress["left"]:
self.my_angle += Stats.hull_t1["left"]
self.angleChange = Stats.hull_t1["left"]
if keypress["right"]:
self.my_angle += Stats.hull_t1["right"]
self.angleChange = Stats.hull_t1["right"]
if keypress["turret_left"]:
self.my_turretAngle += Stats.turret_t1["left"]
self.turretAngleChange = Stats.turret_t1["left"]
if keypress["turret_right"]:
self.my_turretAngle += Stats.turret_t1["right"]
self.turretAngleChange = Stats.turret_t1["right"]
#Tank Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
#Rotate hull image:
with self.hull.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.hull.center
self.rot.angle = self.angleChange
with self.hull.canvas.after:
PopMatrix()
#Rotate turret image:
with self.turret.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.turret.center
self.rot.angle = self.turretAngleChange + self.angleChange
with self.turret.canvas.after:
PopMatrix()
#Reset pos, angle and turretAngle change values:
self.posChange = [0,0]
self.angleChange = 0
self.turretAngleChange = 0
#--------------------------------------------------------------------------------------------------
class Hull(Image):
def __init__(self):
super(Hull, self).__init__(source="images tank/Tank.png")
self.size = self.texture_size
class Turret(Image):
def __init__(self):
super(Turret, self).__init__(source="images tank/GunTurret.png")
self.size = self.texture_size
shot.py:
#Import own modules:
from stats import Stats
#import python:
import math
from copy import copy
#Import Kivy:
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.graphics.context_instructions import PushMatrix, PopMatrix, Rotate, Translate, MatrixInstruction
from kivy.graphics.fbo import Fbo
class Shots(Widget):
def __init__(self, tankPos, turretAngle):
super(Shots, self).__init__()
#Shot data:
self.my_pos = copy(tankPos)
self.my_angle = turretAngle
self.angleChange = self.my_angle
self.posChange = [ -Stats.shot_t1["speed"]*math.sin(math.radians(self.my_angle)), Stats.shot_t1["speed"]*math.cos(math.radians(self.my_angle)) ]
#Add image:
self.shotImg = ShotImg()
self.add_widget(self.shotImg)
self.shotImg.pos = self.my_pos
self.shotImg.center_x = self.my_pos[0]
self.shotImg.center_y = self.my_pos[1]
def update(self):
self.my_pos[0] += self.posChange[0]
self.my_pos[1] += self.posChange[1]
#Shot Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
#Rotate shot image:
if self.angleChange != 0:
with self.shotImg.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.shotImg.center
self.rot.angle = self.angleChange
with self.shotImg.canvas.after:
PopMatrix()
self.angleChange = 0
class ShotImg(Image):
def __init__(self):
super(ShotImg, self).__init__(source="images tank/Bullet.png")
self.size = self.texture_size
stats.py:
class Stats:
winSize = (800,800)
hull_t1 = {"forward":2, "backward":-2, "left":2, "right": -2}
turret_t1 = {"left":5, "right":-5}
shot_t1 = {"speed":3}
images should go in a subfolder called "images tank":
Bullet
GunTurret
Tank
The way you manage your position will create 8 new instructions per tank, and 6 per shot, every frame, which, at 60fps, will quickly create thousands of instructions, and for kivy will be slower and slower to process them.
#Tank Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
you don't want to do that, you want to create one Translate insruction (and same for Rotate) in your widget, and update it, move this block to __init__ and save Translate to self.translate for example, then in update, instead of using posChange, simply do self.translate.x, self.translate.y = self.my_pos
apply the same logic for rotation, and for shots, and the performances should be much more stable over time.
I had the same issue, I'm working on a space invaders game and it happened to be the way I treated my logic, I used "with self.canvas"
to draw my widgets, which appeared to be on the long term exhaustive as widgets that get generated on canvas are not being cleared, which is an important thing to be concerned about.
I Fixed it with creating a class for my objects (enemy, bullet, player) and when I need lets say 6 enemies to be created, I create a list of enemy widgets to keep track of them, and them add them to my on my main game widget by using self.add_widget(YourWidgetItem)
and simply when the widget has ended its purpose, like an enemy dying, I set my dead variable for this widget to be true, then scan for dead widgets and remove them from my main game widget by using self.remove_widget(YourWidgetItem)
this is one of many other possible solutions, you just need to take into consideration killing the widget that get off your screen to no overload your game on higher levels
You can check my project if it would help:
https://github.com/steveroseik/Invaders_Game

Autoresizing Canvas in a Kivy App

I am writing my first Kivy app in python only (I'm avoiding kv for now). I have created a custom widget called WorldviewWidget, and I'm trying to use it as a place to draw. With the button widgets, I just give a size_hint and a pos_hint, and they show up where I want them. But with my widget, I don't know how to use the size_hint and position_hint to size the rectangle I am drawing in my WorldviewWidget. Here is the code. Thanks in advance!
#! /usr/bin/python
from kivy.app import App
from kivy.graphics import *
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class WorldviewWidget(Widget):
def __init__(self, **kwargs):
super(WorldviewWidget, self).__init__(**kwargs)
self.canvas.clear()
print self.size, self.pos
with self.canvas:
Color(1, 0, 0, 1, mode='rgba')
# HELP! I want the rectangle to be resized when the window changes size so that it always takes up the same proportion of the screen.
self.rect = Rectangle(size=???, pos=???)
class JFROCS_App(App):
def build(self):
Window.clearcolor = [1,1,1,1]
parent = FloatLayout(size=Window.size)
worldview = WorldviewWidget(size_hint=(0.4, 0.4), pos_hint = {'x':0.2, 'y':0.2})
parent.add_widget(worldview)
start_btn = Button(text='Start', size_hint=(0.1, 0.1), pos_hint={'x':.02, 'y':.7}, background_color=[0,1,0,1])
start_btn.bind(on_release=self.start_simulation)
parent.add_widget(start_btn)
pause_btn = Button(text='Pause', size_hint=(0.1,0.1), pos_hint={'x':.02, 'y':.6}, background_color=[1,1,0,1])
pause_btn.bind(on_release=self.pause_simulation)
parent.add_widget(pause_btn)
stop_btn = Button(text='Stop', size_hint=(0.1,0.1), pos_hint={'x':.02, 'y':.5}, background_color=[1,0,0,1])
stop_btn.bind(on_release=self.stop_simulation)
parent.add_widget(stop_btn)
return parent
def start_simulation(self, obj):
print "You pushed the start button!"
def pause_simulation(self, obj):
print "You pushed the pause button!"
def stop_simulation(self, obj):
print "You pushed the stop button!"
if __name__ == '__main__':
JFROCS_App().run()
I think that this sort of task is predestined for the kivy-language but here is a solution in Python. Basically, I have used the bind-method to make your widget listen for changes in its parent's size. Have a look at this for more information on this mechanism.
from kivy.app import App
from kivy.graphics import *
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class WorldviewWidget(Widget):
def __init__(self, **kwargs):
super(WorldviewWidget, self).__init__(**kwargs)
self.canvas.clear()
print self.size, self.pos
with self.canvas:
Color(1, 0, 0, 1, mode='rgba')
# *changed* ##############################################
self.rect = Rectangle(size=self.size, pos=self.pos)
# *new* ##########################################################
def update_size(self, instance, new_size):
print "UPDATING SIZE", instance, new_size
self.size[0] = new_size[0] * 0.4
self.size[1] = new_size[1] * 0.4
self.rect.size = self.size
self.pos[0] = self.parent.size[0] * 0.2
self.pos[1] = self.parent.size[1] * 0.2
self.rect.pos = self.pos
class JFROCS_App(App):
def build(self):
Window.clearcolor = [1,1,1,1]
parent = FloatLayout(size=Window.size)
# *changed* ##################################################
worldview = WorldviewWidget(size=(0.4*parent.size[0], 0.4*parent.size[1]),
pos=(0.2*parent.size[0], 0.2*parent.size[1]))
# makes sure that the widget gets updated when parent's size changes:
parent.bind(size=worldview.update_size)
parent.add_widget(worldview)
start_btn = Button(text='Start', size_hint=(0.1, 0.1), pos_hint={'x':.02, 'y':.7}, background_color=[0,1,0,1])
start_btn.bind(on_release=self.start_simulation)
parent.add_widget(start_btn)
pause_btn = Button(text='Pause', size_hint=(0.1,0.1), pos_hint={'x':.02, 'y':.6}, background_color=[1,1,0,1])
pause_btn.bind(on_release=self.pause_simulation)
parent.add_widget(pause_btn)
stop_btn = Button(text='Stop', size_hint=(0.1,0.1), pos_hint={'x':.02, 'y':.5}, background_color=[1,0,0,1])
stop_btn.bind(on_release=self.stop_simulation)
parent.add_widget(stop_btn)
return parent
def start_simulation(self, obj):
print "You pushed the start button!"
def pause_simulation(self, obj):
print "You pushed the pause button!"
def stop_simulation(self, obj):
print "You pushed the stop button!"
if __name__ == '__main__':
JFROCS_App().run()
And have a look at the kivy-language -- it takes care of all the binding for you :)

How can I run simultaneous instances of Clock.schedule_interval in kivy app?

I have a class that changes the background color constantly with a Clock.schedule_interval in init. I would like to create multiple instances of this class simultaneous; however, I think this means creating multiple threads which isn't allowed? What I would like is the top half to be changing colors while the bottom half is changing colors differently. What is happening is only the bottom half is changing colors while the top half is black. So here is the code.
The /teacher/main.py file is
from kivy.app import App
from kivy.clock import Clock
from kivy.graphics import Color
from kivy.properties import NumericProperty, ReferenceListProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
from random import randint
class ChangingBackgroundColor(Widget):
r = NumericProperty(.5)
g = NumericProperty(.5)
b = NumericProperty(.5)
a = NumericProperty(1)
color = ReferenceListProperty(r, g, b, a)
def __init__(self,**kwargs):
super(ChangingBackgroundColor, self).__init__(**kwargs)
Clock.schedule_interval(self.update, .2)
def update(self, dt):
position = randint(0,2) # change to randint(0,3) to change a as well
direction = randint(0,1)
if direction == 0:
if self.color[position] == 0:
self.color[position] += .1
else:
self.color[position] -= .1
elif direction == 1:
if self.color[position] == 1:
self.color[position] -= .1
else:
self.color[position] += .1
self.color[position] = round(self.color[position], 2)
self.canvas.add(Color(self.color))
class TeachingApp(App):
def build(self):
grid = GridLayout(rows=2)
a = ChangingBackgroundColor()
b = ChangingBackgroundColor()
grid.add_widget(a)
grid.add_widget(b)
return grid
if __name__ == '__main__':
TeachingApp().run()
and the /teacher/teaching.kv file is
#:kivy 1.0.9
<ChangingBackgroundColor>:
canvas:
Color:
rgba: self.color
Rectangle:
size: self.width, self.height
I looked here and and still fuzzy on the threading issue. Clock documentation.
This is my first question I have submitted so if I did anything wrong regarding question submission please let me know.
Your code is fine, using Clock.schedule_interval doesn't use threads (it's all in the main thread), and can be used from other threads even if you did have them, although callbacks would still happen in the main thread.
The problem is that your Rectangle entry in the kv needs to have:
pos: self.pos
Without this, both rectangles have the default pos of (0, 0), so the second one is on top of the first one and the top half of the screen is black.

Categories

Resources