Debian Codegraph @

examples/lander/lander.py

raw symbols SCIP
1 import random, math
2
3 """
4 Pi Lander
5 * A basic Lunar Lander style game in Pygame Zero
6 * Run with 'pgzrun pi_lander.py', control with the LEFT, RIGHT and UP arrow keys
7 * Author Tim Martin: www.Tim-Martin.co.uk
8 * Licence: Creative Commons Attribution-ShareAlike 4.0 International
9 * http://creativecommons.org/licenses/by-sa/4.0/
10 """
11
12 WIDTH = 800 # Screen width
13 HEIGHT = 600 # Screen height
14
15 class LandingSpotClass:
16 """ Each instance defines a landing spot by where it starts, how big it is and how many points it's worth """
17 landing_spot_sizes = ["small", "medium", "large"]
18 def __init__(self, starting_step):
19 self.starting = starting_step
20 random_size = random.choice(LandingSpotClass.landing_spot_sizes) # And randomly choose size
21 if random_size == "small":
22 self.size = 4
23 self.bonus = 8
24 elif random_size == "medium":
25 self.size = 10
26 self.bonus = 4
27 else: # Large
28 self.size = 20
29 self.bonus = 2
30 def get_within_landing_spot(self, step):
31 if (step >= self.starting) and (step < self.starting + self.size):
32 return True
33 return False
34
35 class LandscapeClass:
36 """ Stores and generates the landscape, landing spots and star field """
37 step_size = 3 # Landscape is broken down into steps. Define number of pixels on the x axis per step.
38 world_steps = int(WIDTH/step_size) # How many steps can we fit horizontally on the screen
39 small_height_change = 3 # Controls how bumpy the landscape is
40 large_height_change = 10 # Controls how steep the landscape is
41 features = ["mountain","valley","field"] # What features to generate
42 n_stars = 30 # How many stars to put in the background
43 n_spots = 4 # Max number of landing spots to generate
44 def __init__(self):
45 self.world_height = [] # Holds the height of the landscape at each step
46 self.star_locations = [] # Holds the x and y location of the stars
47 self.landing_spots = [] # Holds the landing spots
48 def get_within_landing_spot(self, step):
49 """ Calculate if a given step is within any of the landing spots """
50 for spot in self.landing_spots:
51 if spot.get_within_landing_spot(step) == True:
52 return True
53 return False
54 def get_landing_spot_bonus(self, step):
55 for spot in self.landing_spots:
56 if spot.get_within_landing_spot(step) == True:
57 return spot.bonus
58 return 0
59 def reset(self):
60 """ Generates a new landscape """
61 # First: Choose which steps of the landscape will be landing spots
62 del self.landing_spots[:] # Delete any previous LandingSpotClass objects
63 next_spot_start = 0
64 # Move from left to right adding new landing spots until either
65 # n_spots spots have been placed or we run out of space in the world
66 while len(self.landing_spots) < LandscapeClass.n_spots and next_spot_start < LandscapeClass.world_steps:
67 next_spot_start += random.randint(10, 50) # Randomly choose location to start landing spot
68 new_landing_spot = LandingSpotClass(next_spot_start) # Make a new landing object at this spot
69 self.landing_spots.append( new_landing_spot ) # And store it in our list
70 next_spot_start += new_landing_spot.size # Then take into account its size before choosing the next
71 # Second: Randomise the world map
72 del self.world_height[:] # Clear any previous world height data
73 feature_steps = 0 # Keep track of how many steps we are into a feature
74 self.world_height.append(random.randint(300, 500)) # Start the landscape between 300 and 500 pixels down
75 for step in range(1, LandscapeClass.world_steps):
76 # If feature_step is zero, we need to choose a new feature and how long it goes on for
77 if feature_steps == 0:
78 feature_steps = random.randint(25, 75)
79 current_feature = random.choice(LandscapeClass.features)
80 # Generate the world by setting the range of random numbers, must be flat if in a landing spot
81 if self.get_within_landing_spot(step) == True:
82 max_up = 0 # Flat
83 max_down = 0 # Flat
84 elif current_feature == "mountain":
85 max_up = LandscapeClass.small_height_change
86 max_down = -LandscapeClass.large_height_change
87 elif current_feature == "valley":
88 max_up = LandscapeClass.large_height_change
89 max_down = -LandscapeClass.small_height_change
90 elif current_feature == "field":
91 max_up = LandscapeClass.small_height_change
92 max_down = -LandscapeClass.small_height_change
93 # Generate the next piece of the landscape
94 current_height = self.world_height[step-1]
95 next_height = current_height + random.randint(max_down, max_up)
96 self.world_height.append(next_height)
97 feature_steps -= 1
98 # Stop mountains getting too high, or valleys too low
99 if next_height > 570:
100 current_feature = "mountain" # Too low! Force a mountain
101 elif next_height < 200:
102 current_feature = "valley" # Too high! Force a valley
103 # Third: Randomise the star field
104 del self.star_locations[:]
105 for star in range(0, LandscapeClass.n_stars):
106 star_step = random.randint(0, LandscapeClass.world_steps-1)
107 star_x = star_step * LandscapeClass.step_size
108 star_y = random.randint( 0, self.world_height[star_step] ) # Keep the stars above the landscape
109 self.star_locations.append( (star_x, star_y) )
110
111 class ShipClass:
112 """ Holds the state of the player's ship and handles movement """
113 max_fuel = 1000 # How much fuel the player starts with
114 booster_power = 0.05 # Power of the ship's thrusters
115 rotate_speed = 10 # How fast the ship rotates in degrees per frame
116 gravity = [0., 0.01] # Strength of gravity in the x and y directions
117 def __init__(self):
118 """ Create the variables which will describe the players ship """
119 self.angle = 0 # The angle the ship is facing 0 - 360 degrees
120 self.altitude = 0 # The number of pixels the ship is above the ground
121 self.booster = False # True if the player is firing their booster
122 self.fuel = 0 # Amount of fuel remaining
123 self.position = [0,0] # The x and y coordinates of the players ship
124 self.velocity = [0,0] # The x and y velocity of the players ship
125 self.acceleration = [0,0] # The x and y acceleration of the players ship
126 def reset(self):
127 """ Set the ships position, velocity and angle to their new-game values """
128 self.position = [750., 100.] # Always start at the same spot
129 self.velocity = [ -random.random(), random.random() ] # But with some initial speed
130 self.acceleration = [0., 0.] # No initial acceleration (except gravity of course)
131 self.angle = random.randint(0, 360) # And pointing in a random direction
132 self.fuel = ShipClass.max_fuel # Fill up fuel tanks
133 def rotate(self, direction):
134 """ Rotate the players ship and keep the angle within the range 0 - 360 degrees """
135 if direction == "left":
136 self.angle -= ShipClass.rotate_speed
137 elif direction == "right":
138 self.angle += ShipClass.rotate_speed
139 if self.angle > 360: # Remember than adding or subtracting 360 degrees does not change the angle
140 self.angle -= 360
141 elif self.angle < 0:
142 self.angle += 360
143 def booster_on(self):
144 """ When booster is firing we accelerate in the opposite direction, 180 degrees, from the way the ship is facing """
145 self.booster = True
146 self.acceleration[0] = ShipClass.booster_power * math.sin( math.radians(self.angle + 180) )
147 self.acceleration[1] = ShipClass.booster_power * math.cos( math.radians(self.angle + 180) )
148 self.fuel -= 2;
149 def booster_off(self):
150 """ When the booster is not firing we do not accelerate """
151 self.booster = False
152 self.acceleration[0] = 0.
153 self.acceleration[1] = 0.
154 def update_physics(self):
155 """ Update ship physics in X and Y, apply acceleration (and gravity) to the velocity and velocity to the position """
156 for axis in range(0,2):
157 self.velocity[axis] += ShipClass.gravity[axis]
158 self.velocity[axis] += self.acceleration[axis]
159 self.position[axis] += self.velocity[axis]
160 # Update player altitude. Note that (LanscapeClass.step_size * 3) is the length of the ship's legs
161 ship_step = int(self.position[0]/LandscapeClass.step_size)
162 if ship_step < LandscapeClass.world_steps:
163 self.altitude = game.landscape.world_height[ship_step] - self.position[1] - (LandscapeClass.step_size * 3)
164 def get_out_of_bounds(self):
165 """ Check if the player has hit the ground or gone off the sides """
166 if self.altitude <= 0 or self.position[0] <= 0 or self.position[0] >= WIDTH:
167 return True
168 return False
169
170 class GameClass:
171 """ Holds main game data, including the ship and landscape objects. Checks for game-over """
172 def __init__(self):
173 self.time = 0. # Time spent playing in seconds
174 self.score = 0 # Player's score
175 self.game_speed = 30 # How fast the game should run in frames per second
176 self.time_elapsed = 0. # Time since the last frame was changed
177 self.blink = True # True if blinking text is to be shown
178 self.n_frames = 0 # Number of frames processed
179 self.game_on = False # True if the game is being played
180 self.game_message = "PI LANDER\nPRESS SPACE TO START" # Start of game message
181 self.ship = ShipClass() # Make a object of the ShipClass type
182 self.landscape = LandscapeClass()
183 self.reset() # Start the game with a fresh landscape and ship
184 def reset(self):
185 self.time = 0.
186 self.ship.reset()
187 self.landscape.reset()
188 def check_game_over(self):
189 """ Check if the game is over and update the game state if so """
190 if self.ship.get_out_of_bounds() == False:
191 return # Game is not over
192 self.game_on = False # Game has finished. But did we win or loose?
193 # Check if the player looses. This is if the ship's angle is > 20 degrees
194 # the ship is not over a landing site, is moving too fast or is off the side of the screen
195 ship_step = int(self.ship.position[0]/LandscapeClass.step_size)
196 if self.ship.position[0] <= 0 \
197 or self.ship.position[0] >= WIDTH \
198 or self.landscape.get_within_landing_spot(ship_step) == False \
199 or abs(self.ship.velocity[0]) > .5 \
200 or abs(self.ship.velocity[1]) > .5 \
201 or (self.ship.angle > 20 and self.ship.angle < 340):
202 self.game_message = "YOU JUST DESTROYED A 100 MEGABUCK LANDER\n\nLOOSE 250 POINTS\n\nPRESS SPACE TO RESTART"
203 self.score -= 250
204 else: # If the player has won! Update their score based on the amount of remaining fuel and the landing bonus
205 points = self.ship.fuel / 10
206 points *= self.landscape.get_landing_spot_bonus(ship_step)
207 self.score += points
208 self.game_message = "CONGRATULATIONS\nTHAT WAS A GREAT LANDING!\n\n" + str(round(points)) + " POINTS\n\nPRESS SPACE TO RESTART"
209
210 # Create the game object
211 game = GameClass()
212
213 def draw():
214 """
215 Draw the game window on the screen in the following order:
216 start message, mountain range, bonus points, stars, statistics, player's ship
217 """
218 screen.fill("black")
219 size = LandscapeClass.step_size
220
221 if game.game_on == False:
222 screen.draw.text(game.game_message, center=(WIDTH/2, HEIGHT/5), align="center")
223
224 # Get the x and y coordinates of each step of the landscape and draw it as a straight line
225 for step in range(0, game.landscape.world_steps - 1):
226 x_start = size * step
227 x_end = size * (step + 1)
228 y_start = game.landscape.world_height[step]
229 y_end = game.landscape.world_height[step + 1]
230 screen.draw.line( (x_start, y_start), (x_end, y_end), "white" )
231 # Every second we flash the landing spots with a thicker line by drawing a narrow rectangle
232 if (game.blink == True or game.game_on == False) and game.landscape.get_within_landing_spot(step) == True:
233 screen.draw.filled_rect( Rect(x_start-size, y_start-1, size, 3), "white" )
234
235 # Draw the bonus point notifier
236 if game.blink == True or game.game_on == False:
237 for spot in game.landscape.landing_spots:
238 x_text = spot.starting * size
239 y_text = game.landscape.world_height[ spot.starting ] + 10 # The extra 10 pixels puts the text below the landscape
240 screen.draw.text(str(spot.bonus) + "x", (x_text,y_text), color="white")
241
242 # Draw the stars
243 for star in game.landscape.star_locations:
244 screen.draw.line( star, star, "white" )
245
246 # Draw the stats
247 screen.draw.text("SCORE: " + str(round(game.score)), (10,10), color="white", background="black")
248 screen.draw.text("TIME: " + str(round(game.time)), (10,25), color="white", background="black")
249 screen.draw.text("FUEL: " + str(game.ship.fuel), (10,40), color="white", background="black")
250 screen.draw.text("ALTITUDE: " + str(round(game.ship.altitude)), (WIDTH-230,10), color="white", background="black")
251 screen.draw.text("HORIZONTAL SPEED: {0:.2f}".format(game.ship.velocity[0]), (WIDTH-230,25), color="white", background="black")
252 screen.draw.text("VERTICAL SPEED: {0:.2f}".format(-game.ship.velocity[1]), (WIDTH-230,40), color="white", background="black")
253
254 screen.draw.circle( game.ship.position, size*2, "yellow" ) # Draw the player
255 # Use sin and cosine functions to draw the ship legs and booster at the correct angle
256 # Requires the values in radians (0 to 2*pi) rather than in degrees (0 to 360)
257 sin_angle = math.sin( math.radians(game.ship.angle - 45) ) # Legs are drawn 45 degrees either side of the ship's angle
258 cos_angle = math.cos( math.radians(game.ship.angle - 45) )
259 screen.draw.line( game.ship.position, (game.ship.position[0] + (sin_angle*size*3), game.ship.position[1] + (cos_angle*size*3)), "yellow" )
260 sin_angle = math.sin( math.radians(game.ship.angle + 45) )
261 cos_angle = math.cos( math.radians(game.ship.angle + 45) )
262 screen.draw.line( game.ship.position, (game.ship.position[0] + (sin_angle*size*3), game.ship.position[1] + (cos_angle*size*3)), "yellow" )
263 if game.ship.booster == True:
264 sin_angle = math.sin( math.radians(game.ship.angle) ) # Booster is drawn at the same angle as the ship, just under it
265 cos_angle = math.cos( math.radians(game.ship.angle) )
266 screen.draw.filled_circle( (game.ship.position[0] + (sin_angle*size*3), game.ship.position[1] + (cos_angle*size*3)), size, "orange" )
267
268 def update(detlatime):
269 """ Updates the game physics 30 times every second """
270 game.time_elapsed += detlatime
271 if game.time_elapsed < 1./game.game_speed:
272 return # A 30th of a second has not passed yet
273 game.time_elapsed -= 1./game.game_speed
274
275 # New frame - do all the simulations
276 game.n_frames += 1
277 if game.n_frames % game.game_speed == 0: # If n_frames is an exact multiple of the game FPS: so once per second
278 game.blink = not game.blink # Invert blink so True becomes False or False becomes True
279
280 # Start the game if the player presses space when the game is not on
281 if keyboard.space and game.game_on == False:
282 game.game_on = True
283 game.reset()
284 elif game.game_on == False:
285 return
286
287 # If the game is on, update the movement and the physics
288 if keyboard.left: # Change space ship rotation
289 game.ship.rotate("left")
290 elif keyboard.right:
291 game.ship.rotate("right")
292
293 if keyboard.up and game.ship.fuel > 0: # Fire boosters if the player has enough fuel
294 game.ship.booster_on()
295 else:
296 game.ship.booster_off()
297
298 game.time += detlatime
299 game.ship.update_physics()
300 game.check_game_over()