Home > other >  Python Crash Course 2nd Edition exercise 12-4
Python Crash Course 2nd Edition exercise 12-4

Time:10-16

Have 3 files. rocket_game.py, rocket.py, settings.py. Contents of rocket.py. Key "Up" arrow does nothing. Key "Down" arrow moves the ship up. If I change the last line to "self.y = self.settings.ship_speed", down arrow moves the ship down. But why won't the game hook the up arrow?

def update(self):
    """Update the ship's position based on the moving flag."""

    if self.moving_right and self.rect.right < self.screen_rect.right:
        self.x  = self.settings.ship_speed
    elif self.moving_left and self.rect.left > 0:
        self.x -= self.settings.ship_speed
    if self.moving_up and self.rect.top < self.screen_rect.top:
        self.y  = self.settings.ship_speed
    elif self.moving_down and self.rect.bottom > 0:
        self.y -= self.settings.ship_speed

Key "Up" arrow does nothing. Key "Down" arrow moves the ship up. If I change self.y = self.settings.ship_speed, down arrow moves the ship up, I understand I why. But why doesn't the up arrow?

If I print the events, it sees me pressing the up arrow, but the rocket does not move.

The OTHER issue, the top and bottom boundaries don't seem to exist.

The bottom left corner of the screen is described as being coordinates 0, 0 respectively. I did try setting the bottom boundary as 0, but the ship still flies below the screen. Left and right boundaries work fine. New to python programming, and I tried reading pygame API for rect but it doesn't seem to have the reference that I need. It does list top and bottom rather than up and down. I have tried multiple ways in both the rocket_game.py and rocket.py.

No error messages, and the ultimate goal was to add the ability to move up and down, move left and right, while within the screen_rect borders.

CodePudding user response:

In the pygame coordinate system, the top left coordinate is (0, 0) and the bottom right is (width, height).
Change the moving direction and the condition that prevents the object from moving out of the screen:

if self.moving_up and self.rect.top > 0:
    self.y -= self.settings.ship_speed
elif self.moving_down and self.rect.botom < self.screen_rect.bottom:
    self.y  = self.settings.ship_speed
  • Related