
Re: working on a pyglet tutorial for beginners
Part 9 - just control the playerWhen we ended the last part we had our six types of game objects (player, ball, and red, yellow, grey and dark blocks) on the screen with the soundtrack playing in a loop. Pressing the arrow keys moved all the sprites at once. Of course the movement keys should just move the player sprite, so the first thing to do now is change the movement controls so they affect only the player. To do that, we need to identify the player sprite somehow.
You could do this by writing
player = pyglet.sprite.Sprite() with the appropriate arguments passed to
Sprite(). But we already have a list of the sprites we want -- in out instance of
ImageLoader -- so we can just as well use that. The only thing we'll need to do is change the
sprites list we currently have into a dictionary, like so:
Next the move() function needs to know what it should move -- so just do this by passing another argument to move, a game object. While we're at it speed up the movement speed a little:
 |  |  |
 | Code: def move(direction, sprite, dt): directions = { 'up' : (0, 100), 'down' : (0, -100), 'left' : (-100, 0), 'right' : (100, 0), } dx, dy = directions[direction] sprite.set_position(sprite.x+dx*dt, sprite.y+dy*dt) print sprite, ' moved'
|  |
 |  |  |
And naturally the movement controls should send the correct game object, the player:
 |  |  |
 | Code: input = { key.UP : (move, 'up', sprites['player']), key.DOWN : (move, 'down', sprites['player']), key.LEFT : (move, 'left', sprites['player']), key.RIGHT : (move, 'right', sprites['player']), }
|  |
 |  |  |
However this doesn't work as advertised, because when we call
action(arguments, dt),
arguments is defined as
input[key][1] -- that is, the
1th position of the value tuple for
key, which in this case is only the direction such as 'up'. Fortunately this is easy to change:
conveniently slicing all the values
from the
1th position and putting it in
arguments. Note that we then need to add the '*' to
action in order to unpack the
arguments tuple into a list of arguments, and give an arbitrary name to dt (only named arguments may follow a *series of arguments).
One other minor change is to make sure our random sprite position setting at the beginning still works:
Now the keyboard just controls the player. Next we need to give the player a reason to move around. We'll tackle that in the next part.