def _reset(self): self.spaceship = Spaceship() self.aliens.reset() self.barricades = Barricades() self.score = Score() self.life_counter = LifeCounter() self.is_game_over = False self.delay_since_game_over = 0 self.is_playing = True
def __init__(self): # We create a surface in which sprites will be shown self.window_surface = pygame.display.set_mode(WINDOW_SIZE) # Variables for game loop self.update_time_delay = 0 self.draw_time_delay = 0 # Game state variable self.is_game_over = False self.delay_since_game_over = 0 self.is_playing = True # We create the game entities self.spaceship = Spaceship() self.aliens = Aliens() self.ground = Ground() self.barricades = Barricades() self.score = Score() self.high_score = HighScore() self.life_counter = LifeCounter() self.game_over = GameOver()
def build_scene(self): self.camera = Camera((0.0, -8.0, 1.0), (0,0,1.0)) self.score = Score(0) self.streak = Streak(0) self.atcg_display = ATCGDisplay() self.endzone = EndZone((-1.4,0,-1.3), 2.8, 0.18) self.attaboy = MsgQueue() self.mutation = Mutation(0) if self.win_conditions.has_key('time'): self.timer = Timer(self.win_conditions['time']) else: self.timer = None # speed_dif = self.level * 0.07 * (self.diff*0.8) # spawn_dif = self.level * 0.07 + (self.diff*0.03) ## lower down # self.helix = Helix(speed = 0.7 + speed_dif, spawn_rate=0.7-spawn_dif, # starthgt=7, endhgt=-5, spins=2.5, pair_generator=self.pair_generator) if self.level >= 4: starthgt = 7 endhgt = -2.5 spins = 2.5 else: starthgt = 5 endhgt = -2.5 spins = 1.5 l, d = self.level, self.diff speed_dif = 0.8 + (l * 0.04 * (d*0.6)) spawn_dif = 0.5 - (l * 0.07 * (d*0.09)) self.helix = Helix(speed = speed_dif, spawn_rate=spawn_dif, starthgt=starthgt, endhgt=endhgt, spins=spins, pair_generator=self.pair_generator) self.helix.register_callbacks(self.enter_callback, self.exit_callback) # for n in range(100): # self.helix.update(0.1) self.attaboy.add_centered_fade("level %d\n%s\n%s" % (self.level, diff[self.diff], messages.EASY_LEVELS[self.level]), 0.2, 0.1)
def run(screen): """main game""" show_fps = True if '--fps' in sys.argv else False show_rects = True if '--show_rects' in sys.argv else False fps = 60 if '--no_limit' in sys.argv else 240 fuel = 10000 ground = location.Ground(450) background = location.Background() box = pygame.Rect((-100, 10), (1100, 600)) lunar_module = LunarModule((400, 100), 1.62, fuel) lunar_module.set_box(box) controll_panel = ControllPanel((700, 20)) ui_score = Score((10, 10)) cm_rect = pygame.Rect((0, 0), screen.get_size()) running = True boulders = gen_landscape(box.bottom, location.Boulder, (box.left, box.right)) fps_clock = pygame.time.Clock() deltat = 0 score = 0 stop_timer = None landing_points = pygame.sprite.Group() game_over_text = GameOverText() game_over_sound = pygame.mixer.Sound("sound/game_over.ogg") while running: pygame.event.pump() events = pygame.event.get() keys_pressed = pygame.key.get_pressed() for event in events: if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.QUIT: sys.exit() if stop_timer and stop_timer.has_expired(): running = False #update lunarmodule and camera_position update_lm(lunar_module, events, keys_pressed) lunar_module.update(deltat, boulders, SOUND) cm_rect.center = lunar_module.rect.center #location screen.blit(background.image, background.rect) ground.update(cm_rect) advanced_draw(screen, ground.image, ground.rect, show_rects, cm_rect) #landing points score += manage_lps(lunar_module, landing_points) draw_group(landing_points, screen, cm_rect, show_rects) #draw boulders draw_group(boulders, screen, cm_rect, show_rects) #draw lunar module advanced_draw(screen, lunar_module.shadow.image, lunar_module.shadow.rect, show_rects, cm_rect) draw(screen, lunar_module.image, lunar_module.image.get_rect(center=(400, 300)), show_rects) if show_rects: box_rect = local_rect(lunar_module.box, cm_rect) pygame.draw.rect(screen, (255, 255, 255), box_rect, 2) lm_rect = local_rect(lunar_module.rect, cm_rect) pygame.draw.rect(screen, (255, 255, 255), lm_rect, 2) #controllpanel velocity = math.sqrt(lunar_module.velocity[0] ** 2 + lunar_module.velocity[1] ** 2) direction = math.degrees(math.atan2(lunar_module.velocity[1], lunar_module.velocity[0])) direction = 270 - direction if lunar_module.velocity[1] == lunar_module.velocity[0] == 0: direction = 0 controll_panel.update(lunar_module.altitude, velocity, direction, lunar_module.fuel / float(fuel)) draw(screen, controll_panel.image, controll_panel.rect, show_rects) ui_score.update(score) screen.blit(ui_score.image, ui_score.position) if lunar_module.game_over: if not stop_timer: stop_timer = Timer(5) pygame.mixer.Channel(0).fadeout(2) if SOUND: game_over_sound.play() game_over_text.update(1 + stop_timer.get_state()) advanced_draw(screen, game_over_text.image, game_over_text.rect, show_rects) deltat = fps_clock.tick(fps) / 1000.0 if show_fps: print 1 / deltat pygame.display.update() check_score(score, SCREEN)
def run(screen): """main game""" show_fps = True if '--fps' in sys.argv else False show_rects = True if '--show_rects' in sys.argv else False fps = 60 if '--no_limit' in sys.argv else 240 fuel = 10000 ground = location.Ground(450) background = location.Background() box = pygame.Rect((-100, 10), (1100, 600)) lunar_module = LunarModule((400, 100), 1.62, fuel) lunar_module.set_box(box) controll_panel = ControllPanel((700, 20)) ui_score = Score((10, 10)) cm_rect = pygame.Rect((0, 0), screen.get_size()) running = True boulders = gen_landscape(box.bottom, location.Boulder, (box.left, box.right)) fps_clock = pygame.time.Clock() deltat = 0 score = 0 stop_timer = None landing_points = pygame.sprite.Group() game_over_text = GameOverText() game_over_sound = pygame.mixer.Sound("sound/game_over.ogg") while running: pygame.event.pump() events = pygame.event.get() keys_pressed = pygame.key.get_pressed() for event in events: if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.QUIT: sys.exit() if stop_timer and stop_timer.has_expired(): running = False #update lunarmodule and camera_position update_lm(lunar_module, events, keys_pressed) lunar_module.update(deltat, boulders, SOUND) cm_rect.center = lunar_module.rect.center #location screen.blit(background.image, background.rect) ground.update(cm_rect) advanced_draw(screen, ground.image, ground.rect, show_rects, cm_rect) #landing points score += manage_lps(lunar_module, landing_points) draw_group(landing_points, screen, cm_rect, show_rects) #draw boulders draw_group(boulders, screen, cm_rect, show_rects) #draw lunar module advanced_draw(screen, lunar_module.shadow.image, lunar_module.shadow.rect, show_rects, cm_rect) draw(screen, lunar_module.image, lunar_module.image.get_rect(center=(400, 300)), show_rects) if show_rects: box_rect = local_rect(lunar_module.box, cm_rect) pygame.draw.rect(screen, (255, 255, 255), box_rect, 2) lm_rect = local_rect(lunar_module.rect, cm_rect) pygame.draw.rect(screen, (255, 255, 255), lm_rect, 2) #controllpanel velocity = math.sqrt(lunar_module.velocity[0]**2 + lunar_module.velocity[1]**2) direction = math.degrees( math.atan2(lunar_module.velocity[1], lunar_module.velocity[0])) direction = 270 - direction if lunar_module.velocity[1] == lunar_module.velocity[0] == 0: direction = 0 controll_panel.update(lunar_module.altitude, velocity, direction, lunar_module.fuel / float(fuel)) draw(screen, controll_panel.image, controll_panel.rect, show_rects) ui_score.update(score) screen.blit(ui_score.image, ui_score.position) if lunar_module.game_over: if not stop_timer: stop_timer = Timer(5) pygame.mixer.Channel(0).fadeout(2) if SOUND: game_over_sound.play() game_over_text.update(1 + stop_timer.get_state()) advanced_draw(screen, game_over_text.image, game_over_text.rect, show_rects) deltat = fps_clock.tick(fps) / 1000.0 if show_fps: print 1 / deltat pygame.display.update() check_score(score, SCREEN)
class GameState (State): def __init__(self, window, level, diff, pair_generator, win_conditions, *args, **kwargs): print "++++ new game state" self.level = level self.diff = diff self.pair_generator = pair_generator self.win_conditions = win_conditions State.__init__(self, window, "game", *args, **kwargs) self.build_scene() self.current_rung = None self.longest_streak = 0 self.time = 0 self.mutation_counter = 0 def build_scene(self): self.camera = Camera((0.0, -8.0, 1.0), (0,0,1.0)) self.score = Score(0) self.streak = Streak(0) self.atcg_display = ATCGDisplay() self.endzone = EndZone((-1.4,0,-1.3), 2.8, 0.18) self.attaboy = MsgQueue() self.mutation = Mutation(0) if self.win_conditions.has_key('time'): self.timer = Timer(self.win_conditions['time']) else: self.timer = None # speed_dif = self.level * 0.07 * (self.diff*0.8) # spawn_dif = self.level * 0.07 + (self.diff*0.03) ## lower down # self.helix = Helix(speed = 0.7 + speed_dif, spawn_rate=0.7-spawn_dif, # starthgt=7, endhgt=-5, spins=2.5, pair_generator=self.pair_generator) if self.level >= 4: starthgt = 7 endhgt = -2.5 spins = 2.5 else: starthgt = 5 endhgt = -2.5 spins = 1.5 l, d = self.level, self.diff speed_dif = 0.8 + (l * 0.04 * (d*0.6)) spawn_dif = 0.5 - (l * 0.07 * (d*0.09)) self.helix = Helix(speed = speed_dif, spawn_rate=spawn_dif, starthgt=starthgt, endhgt=endhgt, spins=spins, pair_generator=self.pair_generator) self.helix.register_callbacks(self.enter_callback, self.exit_callback) # for n in range(100): # self.helix.update(0.1) self.attaboy.add_centered_fade("level %d\n%s\n%s" % (self.level, diff[self.diff], messages.EASY_LEVELS[self.level]), 0.2, 0.1) def enter_callback(self, r): self.current_rung = r def exit_callback(self, r): if r.get_pair_data()[0] == None or r.get_pair_data()[1] == None: self.bad_move() self.current_rung = None def destroy_scene(self): pass def on_draw(self): set3D(self.window) self.window.clear() glLoadIdentity() self.camera.focus() batch.get_batch().draw() set2D(self.window) return pyglet.event.EVENT_HANDLED def bad_move(self): audio.play_sound('lose_streak') r = self.current_rung if r: r.miss() self.camera.shake(1,2, 1) self.attaboy.add_centered_fade(messages.random_bad_move(), 0.25, 1, ([0.7,0.7,0.7,1.0], [0.1,0.1,0.1,1.0])) self.streak.reset() l, d = self.level, self.diff self.helix.mutate(0.2 + (l * 0.04)) self.mutation_counter += 5 * (self.level*0.5) if self.mutation_counter > 100: self.lose() self.mutation.set_mutation(self.mutation_counter) def good_move(self): audio.play_sound('hit') r = self.current_rung if r: r.hit() if self.mutation_counter > 1: self.mutation_counter -= 1 self.mutation.set_mutation(self.mutation_counter) s = self.streak.inc() p = s*0.5*100 self.attaboy.add_score_fade(p) self.score.inc_score(p) def on_key_press(self, k, args): ## =A++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=== if k == key.A: self.atcg_display.A.on() if check_hit('A', self.current_rung): self.good_move() else: self.bad_move() ## =S++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=== elif k == key.S: self.atcg_display.T.on() if check_hit('T', self.current_rung): self.good_move() else: self.bad_move() ## =D++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=== elif k == key.D: self.atcg_display.C.on() if check_hit('C', self.current_rung): self.good_move() else: self.bad_move() ## =F++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=== elif k == key.F: self.atcg_display.G.on() if check_hit('G', self.current_rung): self.good_move() else: self.bad_move() ## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++= elif k == key.LEFT: pass elif k == key.RIGHT: pass elif k == key.ESCAPE: self.pause() return pyglet.event.EVENT_HANDLED elif k == key.F11: if self.window.fullscreen: self.window.set_fullscreen(False) else: self.window.set_fullscreen(True) return pyglet.event.EVENT_HANDLED def on_key_release(self, k, args): if k == key.A: self.atcg_display.A.off() elif k == key.S: self.atcg_display.T.off() elif k == key.D: self.atcg_display.C.off() elif k == key.F: self.atcg_display.G.off() return pyglet.event.EVENT_HANDLED def on_mouse_scroll(self, x, y, scroll_x, scroll_y): pass def lose(self): self.window.pop_state() self.window.replace_state(transitions.ScriptedTransition, script=script.lose, script_name="lose") def win(self): self.window.replace_state(transitions.ScriptedTransition, script=script.win, script_name="win") def on_lose_focus(self): pyglet.clock.unschedule(self.on_update) return pyglet.event.EVENT_HANDLED def on_gain_focus(self): self.helix.unobscure() self.helix.update(0.1) pyglet.clock.schedule_interval(self.on_update, 1.0/60.0) return pyglet.event.EVENT_HANDLED def check_win_conditions(self): if self.win_conditions.has_key('score'): if self.score.points > self.win_conditions['score']: self.win() elif self.win_conditions.has_key('streak'): if self.streak.streak >= self.win_conditions['streak']: self.win() elif self.win_conditions.has_key('time'): if self.timer.time < 0: self.win() def on_update(self, dt): self.camera.update(dt) self.attaboy.update(dt) self.atcg_display.update(dt) self.check_win_conditions() self.helix.update(dt) if self.win_conditions.has_key('time'): self.timer.update_time(dt) def pause(self): self.helix.obscure() self.helix.update(0.1) self.window.push_state(transitions.Pause, "game")
class PySpaceInvaders: def __init__(self): # We create a surface in which sprites will be shown self.window_surface = pygame.display.set_mode(WINDOW_SIZE) # Variables for game loop self.update_time_delay = 0 self.draw_time_delay = 0 # Game state variable self.is_game_over = False self.delay_since_game_over = 0 self.is_playing = True # We create the game entities self.spaceship = Spaceship() self.aliens = Aliens() self.ground = Ground() self.barricades = Barricades() self.score = Score() self.high_score = HighScore() self.life_counter = LifeCounter() self.game_over = GameOver() def play(self): clock = pygame.time.Clock() while True: dt = clock.tick() update_count = self._get_update_count(dt) if update_count > 0: # If game over for too long, reset the game if self.is_game_over: self.delay_since_game_over += update_count * UPDATE_PERIOD_MS if self.delay_since_game_over > GAME_OVER_DURATION_S * 1000: self._reset() # This update the entities from the game self._update(update_count * UPDATE_PERIOD_MS) # Here, it's all the update that involves several entities, like collision self._update_life_count() self._collide() frame_count = self._get_frame_count(dt) if frame_count > 0: self._draw() def _update(self, dt): # Getting input events events = self._get_events() # Updating each entity self.spaceship.update(dt, events) self.aliens.update(dt) def _update_life_count(self): if self.score.value // ONE_LIFE_SCORE > self.life_counter.life_gain_count: self.life_counter.one_up() if not self.spaceship.is_active: if self.life_counter.life_count > 0: self.life_counter.life_count -= 1 self.spaceship.reset() else: self._game_over() def _get_update_count(self, dt): # Incrementing the delay since previous update self.update_time_delay += dt # Count how many updates should be done. If more than one, a warning is shown update_count = self.update_time_delay // UPDATE_PERIOD_MS if update_count > 1: print(str(update_count - 1) + " updates are late.") self.update_time_delay = self.update_time_delay % UPDATE_PERIOD_MS return update_count def _get_events(self): events = [] for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() events.append(event) return events def _draw(self): # First we clear everything from screen self.window_surface.fill(( 0, 0, 0, )) # We draw each entity self.ground.draw(self.window_surface) self.barricades.draw(self.window_surface) self.spaceship.draw(self.window_surface) self.aliens.draw(self.window_surface) self.score.draw(self.window_surface) self.high_score.draw(self.window_surface) self.life_counter.draw(self.window_surface) if self.is_game_over: self.game_over.draw(self.window_surface) # We show the screen pygame.display.flip() def _get_frame_count(self, dt): # Incrementing delay since previous frame self.draw_time_delay += dt # We count how many frames we should draw. If more than one, we show a warning. frame_count = self.draw_time_delay // DRAW_PERIOD_MS if frame_count > 1: print("Skipping " + str(frame_count - 1) + " frames") self.draw_time_delay = self.draw_time_delay % DRAW_PERIOD_MS return frame_count def _collide(self): self._collide_missile_and_aliens() self._collide_spaceship_and_aliens() self._collide_spaceship_and_lasers() self._collide_missile_and_lasers() self._collide_missile_and_barricades() self._collide_laser_and_barricades() self._collide_alien_and_barricades() self._collide_missile_and_saucer() def _collide_missile_and_aliens(self): # If no missile, no collision to check if not self.spaceship.missile.is_active: return # Get rectangle from missile missile_rect = self.spaceship.missile.rect # Get each alien rectangle and check collision for alien in self.aliens: if missile_rect.colliderect(alien.rect): # if collision, make the alien explode and remove missile alien.explode() self.spaceship.missile.is_active = False # increase score self.score.value += alien.type * 10 def _collide_missile_and_saucer(self): # If no missile or no saucer if not self.spaceship.missile.is_active or not self.aliens.saucer.is_active: return # Get rectangle from missile and saucer missile_rect = self.spaceship.missile.rect saucer_rect = self.aliens.saucer.rect # if collision, make the saucer explode and remove missile if missile_rect.colliderect(saucer_rect): self.aliens.saucer.explode() self.spaceship.missile.is_active = False # increase score self.score.value += 300 def _collide_spaceship_and_aliens(self): # Get each alien rect and check collision with spaceship for alien in self.aliens: # If spaceship already destroyed, we stop. if self.spaceship.is_destroyed: return if alien.rect.colliderect(self.spaceship.rect): self.spaceship.destroy() def _collide_spaceship_and_lasers(self): # If spaceship already destroyed, we return if self.spaceship.is_destroyed: return # Get each laser rectangle and spaceship rectangle laser_rect_list = [laser.rect for laser in self.aliens.lasers] spaceship_rect = self.spaceship.rect if spaceship_rect.collidelist(laser_rect_list) != -1: self.spaceship.destroy() def _collide_missile_and_lasers(self): # If no missile, no collision to check if not self.spaceship.missile.is_active: return # Get each laser rectangle and missile rectangle laser_rect_list = [laser.rect for laser in self.aliens.lasers] missile_rect = self.spaceship.missile.rect # If collision, we remove both laser_index = missile_rect.collidelist(laser_rect_list) if laser_index != -1: self.spaceship.missile.explode() self.aliens.lasers[laser_index].explode() def _collide_missile_and_barricades(self): # If no missile, no collision to check if not self.spaceship.missile.is_active: return # If collision, update barricade sprite and destroy missile if self._collide_with_barricades(self.spaceship.missile, MISSILE_BARRICADE_EXPLOSION_RADIUS): self.spaceship.missile.is_active = False def _collide_laser_and_barricades(self): # If collision, update barricade sprite and destroy laser for laser in self.aliens.lasers: if self._collide_with_barricades(laser, LASER_BARRICADE_EXPLOSION_RADIUS): laser.explode() def _collide_alien_and_barricades(self): # If collision, update barricade sprite only, alien continue to live for alien in self.aliens: self._collide_with_barricades(alien, LASER_BARRICADE_EXPLOSION_RADIUS) def _collide_with_barricades(self, shoot, radius): for barricade in self.barricades: # Find a colliding pixel collision_point = self._find_colliding_pixel(shoot, barricade) # Handle collision if there is one if collision_point: self._apply_explosion_on_mask(collision_point, radius, barricade) self._build_sprite_from_mask(barricade) return True return False def _find_colliding_pixel(self, shoot, barricade): # get distance vector between top left of barricade and colliding entity x, y = (shoot.rect.x, shoot.rect.y) offset = (x - barricade.rect.x, y - barricade.rect.y) # Using mask to get collision point w, h = (shoot.rect.w, shoot.rect.h) shoot_mask = pygame.Mask((w, h), fill=True) return barricade.mask.overlap(shoot_mask, offset) def _apply_explosion_on_mask(self, collision_point, radius, barricade): # At collision point, remove pixels cx, cy = collision_point barricade.mask.set_at((cx, cy), 0) # Loop on each pixel around collision point for x in range(cx - radius, cx + radius + 1, 1): for y in range(cy - radius, cy + radius + 1, 1): # If not in barricade sprite, continue if x < 0 or x >= barricade.rect.w or y < 0 or y >= barricade.rect.h: continue # if not in the circle around collision, continue if math.sqrt((x - cx)**2 + (y - cy)**2) > radius: continue # We remove the pixel under a given probability if random.random() < BARRICADE_DESTRUCTION_PROBABILITY: barricade.mask.set_at((x, y), 0) def _build_sprite_from_mask(self, barricade): # create an surfarray and change pixel color according to mask surf_array = pygame.surfarray.array3d(barricade.sprite) for y in range(barricade.rect.h): for x in range(barricade.rect.w): if barricade.mask.get_at((x, y)) == 0: surf_array[x, y] = (0, 0, 0) # make sprite from surfarray. barricade.sprite = pygame.surfarray.make_surface(surf_array) def _game_over(self): self.is_game_over = True self.is_playing = False if self.score.value > self.high_score.value: self.high_score.value = self.score.value def _reset(self): self.spaceship = Spaceship() self.aliens.reset() self.barricades = Barricades() self.score = Score() self.life_counter = LifeCounter() self.is_game_over = False self.delay_since_game_over = 0 self.is_playing = True