Alex Z writes (edited):
I'm playing with the last chapter game, cf. the stickmangame7.py file. I'm a little confused about how the key presses are expected to cause the character [to] move.
If the player hits the right or left key, the character starts moving but keeps moving and doesn't stop unless [colliding] against a wall or a platform. Even jumping on a platform doesn't cause the stick figure to stop. This makes hard to climb to the top parts of the area. Is it the expected behavior of the game ?
I am not the first to experience this problem, see the folowing message on stackoverflow: How to move character only when key is pressed down Python
Yes, that is the expected behaviour of the game. The point is to make it more difficult to reach the top platform, so once the character starts running he doesn't stop, unless he collides with something. However, if you do want to change it so that the character only moves when the key is held down, there's a few fairly minor modifications you can make (which are discussed in that stack overflow article):
i. Add a new function to stop the character moving, by changing the value of the x
variable to 0. So in the StickFigureSprite sprite class we add this new function:
class StickFigureSprite(Sprite):
...
...
...
def stop_moving(self, evt):
self.x = 0
ii. Now we need a way to call the new function. So we add two new key bindings to the __init__
function of the same class, and set the starting value of the x
variable to 0 (it's currently set to -2 so that the stick figure starts running as soon as the game starts):
class StickFigureSprite(Sprite):
def __init__(self, game):
...
...
self.x = 0
...
...
game.canvas.bind_all('<KeyRelease-Left>', self.stop_moving)
game.canvas.bind_all('<KeyRelease-Right>', self.stop_moving)
So with these changes the game starts and the stick man won't move. When you hold the left or right key down, the x
variable is set to -2 or 2 respectively which starts "him" moving. When you release the key, it sets the value back to 0, which stops him moving again.
You might notice one slight problem when running the game after this change - the stickman starts quickly and then slows down. This is caused by the keyboard repeating which then impacts the performance of the mainloop
function in the Game class. This is an unfortunate side effect of the way the code for the game is written (the stickman code is not the standard way to handle animation with tkinter -- however it was written this way to hopefully make animation concepts, in programming, slightly easier for a child to understand).