def __init__(self, *args, **kwargs): super(GameWindow, self).__init__(*args, **kwargs) self.main_batch = pyglet.graphics.Batch() self.player = load.create_player(self.main_batch) self.player_lives = load.player_lives(3, self.main_batch) self.aliens = load.aliens(self.main_batch) self.game_objects = [self.player] + self.aliens self.score_label = score.Score(text = "Score: 0", x = 10, y = 10, batch=self.main_batch) self.game_over_text = pyglet.text.Label( text = "Game Over!", font_size = 26, x = 100, y = self.height / 2) self.game_over_restart_text = pyglet.text.Label( text = "Press space to restart", font_size = 26, x = 100, y = (self.height / 2) - 50) self.start_text = pyglet.text.Label(text = "Press space to start", font_size = 26, x = 100, y = self.height / 2) self.is_paused = True self.is_game_over = False
def update(self, dt): if self.is_paused: return # Check for collisions for i in range(len(self.game_objects)): for j in range(i+1, len(self.game_objects)): obj_1 = self.game_objects[i] obj_2 = self.game_objects[j] if not obj_1.dead and not obj_2.dead: if obj_1.collides_with(obj_2): obj_1.handle_collision_with(obj_2) obj_2.handle_collision_with(obj_1) # Call update methods of all objects & add any new objects for obj in self.game_objects: obj.update(dt) self.game_objects.extend(obj.new_objects) obj.new_objects = [] if random.randint(1, 1000) < 5: self.game_objects.extend([load.create_mothership(self.main_batch)]) to_add = [] # Remove any objects marked as dead for to_remove in [obj for obj in self.game_objects if obj.dead]: # Score if type(to_remove) is type(alien.Alien()): # Increase alien speed (it gets ridiculous very quickly) alien.Alien.speed += 0.05 self.score_label.add(100) self.score_label.update(dt) if type(to_remove) is type(mothership.Mothership()): if to_remove.carries_score: self.score_label.add(500) self.score_label.update(dt) # Life handling if type(to_remove) is type(player.Player()): # Decrement life counter & respawn handler if len(self.player_lives) > 0: del self.player_lives[-1] # De-register key handlers self.remove_handlers(to_remove) self.remove_handlers(to_remove.key_handler) # Define new player new_player = load.create_player(self.main_batch) # Re-register new key handlers self.push_handlers(new_player) self.push_handlers(new_player.key_handler) # Add it to the 'to_add' list to_add.append(new_player) else: """ Game Over De-register key handlers: This prevents errors occurring due to the lack of a player object :( """ self.remove_handlers(to_remove) self.remove_handlers(to_remove.key_handler) self.is_paused = True self.is_game_over = True to_remove.delete() self.game_objects.remove(to_remove) self.game_objects.extend(to_add)