Moving Both Left and Right
Now that the ship can move continuously to the right, adding movement
to the left is straightforward. Again, we’ll modify the Ship class and the
_check_events() method. Here are the relevant changes to __init__() and
update() in Ship:
[Link] def __init__(self, ai_game):
--snip--
# Movement flags; start with a ship that's not moving.
self.moving_right = False
self.moving_left = False
def update(self):
"""Update the ship's position based on movement flags."""
if self.moving_right:
[Link].x += 1
if self.moving_left:
[Link].x -= 1
In __init__(), we add a self.moving_left flag. In update(), we use two
separate if blocks, rather than an elif, to allow the ship’s rect.x value to be
increased and then decreased when both arrow keys are held down. This
results in the ship standing still. If we used elif for motion to the left, the
right arrow key would always have priority. Using two if blocks makes the
movements more accurate when the player might momentarily hold down
both keys when changing directions.
We have to make two additions to _check_events():
alien_invasion.py def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in [Link]():
--snip--
elif [Link] == [Link]:
if [Link] == pygame.K_RIGHT:
[Link].moving_right = True
elif [Link] == pygame.K_LEFT:
[Link].moving_left = True
elif [Link] == [Link]:
if [Link] == pygame.K_RIGHT:
[Link].moving_right = False
elif [Link] == pygame.K_LEFT:
[Link].moving_left = False
If a KEYDOWN event occurs for the K_LEFT key, we set moving_left to True. If a
KEYUP event occurs for the K_LEFT key, we set moving_left to False. We can use
elif blocks here because each event is connected to only one key. If the player
presses both keys at once, two separate events will be detected.
When you run alien_invasion.py now, you should be able to move the
ship continuously to the right and left. If you hold down both keys, the ship
should stop moving.
A Ship That Fires Bullets 241