sprite - How to move character only when key is pressed down Python. -


i have been working through book called python kids. last project in book platforming game. game called mr stick man races exit. way move character (a stickman) press left or right , move left or right. unlike games, if let go of key, keeps moving. how make stop when key released?

here link download of code: https://www.nostarch.com/pythonforkids

if press download sample code book, program "stickmangame7" in chapter 18 folder. have included link in case embedded wrong bit on code.

here embedded code may correct bit:

class stickfiguresprite(sprite): def __init__(self, game):     sprite.__init__(self, game)     self.images_left = [         photoimage(file="stick-l1.gif"),         photoimage(file="stick-l2.gif"),         photoimage(file="stick-l3.gif")     ]     self.images_right = [         photoimage(file="stick-r1.gif"),         photoimage(file="stick-r2.gif"),         photoimage(file="stick-r3.gif")     ]     self.image = game.canvas.create_image(200, 470, image=self.images_left[0], anchor='nw')     self.x = -2     self.y = 0     self.current_image = 0     self.current_image_add = 1     self.jump_count = 0     self.last_time = time.time()     self.coordinates = coords()     game.canvas.bind_all('<keypress-left>', self.turn_left)     game.canvas.bind_all('<keypress-right>', self.turn_right)     game.canvas.bind_all('<space>', self.jump) 

also:

 def turn_left(self, evt):     if self.y == 0:         self.x = -2  def turn_right(self, evt):     if self.y == 0:         self.x = 2 

p.s. know can using pygame, not using pygame rest, don't think work.

without looking @ rest of code, given turn_left() , turn_right() methods modifying self.x assume in event loop value used calculate movement of 'stick' on x axis. want reset 0 when key gets released, create additional method example:

def stop_movement(self, evt):     self.x = 0 

and when binding keypress events, bind keyrelease events method, e.g.:

game.canvas.bind_all('<keyrelease-left>', self.stop_movement) game.canvas.bind_all('<keyrelease-right>', self.stop_movement) 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -