# Movement flag; start with a ship that's not moving.
1 self.moving_right = False
2 def update(self):
"""Update the ship's position based on the movement flag."""
if self.moving_right:
[Link].x += 1
def blitme(self):
--snip--
We add a self.moving_right attribute in the __init__() method and set it
to False initially 1. Then we add update(), which moves the ship right if the
flag is True 2. The update() method will be called from outside the class, so
it’s not considered a helper method.
Now we need to modify _check_events() so that moving_right is set to True
when the right arrow key is pressed and False when the key is released:
alien def _check_events(self):
_invasion.py """Respond to keypresses and mouse events."""
for event in [Link]():
--snip--
elif [Link] == [Link]:
if [Link] == pygame.K_RIGHT:
1 [Link].moving_right = True
2 elif [Link] == [Link]:
if [Link] == pygame.K_RIGHT:
[Link].moving_right = False
Here, we modify how the game responds when the player presses the
right arrow key: instead of changing the ship’s position directly, we merely
set moving_right to True 1. Then we add a new elif block, which responds to
KEYUP events 2. When the player releases the right arrow key (K_RIGHT), we
set moving_right to False.
Next, we modify the while loop in run_game() so it calls the ship’s update()
method on each pass through the loop:
alien_invasion.py def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
[Link]()
self._update_screen()
[Link](60)
The ship’s position will be updated after we’ve checked for keyboard
events and before we update the screen. This allows the ship’s position to be
updated in response to player input and ensures the updated position will
be used when drawing the ship to the screen.
When you run alien_invasion.py and hold down the right arrow key, the
ship should move continuously to the right until you release the key.
240 Chapter 12