Rotating the Ship


For my next task, I introduce the player's ship. My modest goal is to allow a user to rotate the ship with the arrow keys. I plan to attack the other ship functions later.

The Astrocrash02 Program

The Astrocrash02 program extends Astrocrash01. In the new version, I create a ship at the center of the screen that the user can rotate. If the user presses the Right Arrow key, the ship rotates clockwise. If the user presses the Left Arrow key, the ship rotates counterclockwise. Figure 12.9 shows the program in action.

click to expand
Figure 12.9: The player's ship is now part of the action.

The Ship Class

The main thing I have to do is write a Ship class for the player's ship:

 class Ship(games.Sprite):     """ The player's ship. """     image = games.load_image("ship.bmp")     ROTATION_STEP = 3     def __init__(self, screen, x, y):         """ Initialize ship sprite. """         self.init_sprite(screen = screen, x = x, y = y, image = Ship.image)     def moved(self):         """ Rotate the ship based on key presses. """         # rotate based on left and right arrow keys         if self.screen.is_pressed(games.K_LEFT):             self.rotate_by(-Ship.ROTATION_STEP)         if self.screen.is_pressed(games.K_RIGHT):             self.rotate_by(Ship.ROTATION_STEP) 

This class is taken almost directly from the Rotate Sprite program. In fact, there are only two, small differences worth noting. First, I load the image of the ship and assign the resulting image object to the class variable image. Second, I use the class constant ROTATION_STEP for the number of degrees by which the ship rotates when the user presses the Left or Right Arrow keys.

Instantiating a Ship Object

The last thing I do is instantiate a Ship object. I create a new ship in the middle of the screen in the main part of the program:

 # create the ship Ship(screen = my_screen, x = SCREEN_WIDTH / 2, y = SCREEN_HEIGHT / 2) 




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net