Esempio n. 1
0
class Space_Invader:
    def __init__(self):
        pygame.init()
        # Set up the music
        self.shoot_sound = pygame.mixer.Sound('music/8bit.wav')
        pygame.mixer.music.load('music/09 - Cherry Bomb.mp3')
        pygame.mixer.music.play(-1, 0.0)
        self.music_playing = True

        self.settings = settings()
        self.scene = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height), 0, 32)
        pygame.display.set_caption('Space Invader')
        self.fleet = Fleet(self.settings, self.shoot_sound)
        self.ship = Ship(self.settings)
        self.start_screen = start_screen(
            self.scene,
            Vector2(self.settings.screen_width, self.settings.screen_height),
            self.settings)
        self.high_score_screen = high_score_screen(self.scene, self.settings)
        self.game_over_screen = game_over_screen(self.settings, self.scene)

        # Set up the music
        self.shoot_sound = pygame.mixer.Sound('music/8bit.wav')
        pygame.mixer.music.load('music/09 - Cherry Bomb.mp3')
        pygame.mixer.music.play(-1, 0.0)
        self.music_playing = True

        self.new_game = True
        self.show_scores = False
        self.game_over = False
        self.round_count = 1

        self.scene_count = 0

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        if self.new_game:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    button_clicked = self.start_screen.play_game_button.rect.collidepoint(
                        mouse_pos)
                    if button_clicked:
                        self.new_game = False
                        self.show_scores = False
                        self.game_over = False
                    button_clicked = self.start_screen.high_score_button.rect.collidepoint(
                        mouse_pos)
                    if button_clicked:
                        self.new_game = False
                        self.show_scores = True
        elif self.show_scores:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    button_clicked = self.high_score_screen.return_button.rect.collidepoint(
                        mouse_pos)
                    if button_clicked:
                        self.new_game = True
                        self.show_scores = False
                        self.game_over = False
        elif self.game_over:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    button_clicked = self.game_over_screen.button1.rect.collidepoint(
                        mouse_pos)
                    if button_clicked:
                        self.show_scores = True
                        self.game_over = False
                        self.new_game = False
                        self.fleet = Fleet(self.settings)
                        self.ship = Ship(self.settings)
                    button_clicked = self.game_over_screen.button2.rect.collidepoint(
                        mouse_pos)
                    if button_clicked:
                        self.show_scores = False
                        self.game_over = False
                        self.new_game = False
                        self.fleet = Fleet(self.settings)
                        self.ship = Ship(self.settings)
        else:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    self._check_keydown_events(event)
                elif event.type == pygame.KEYUP:
                    self._check_keyup_events(event)
                #elif event.type == pygame.MOUSEBUTTONDOWN:
                #   mouse_pos = pygame.mouse.get_pos()
                #  self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        if self.new_game:
            pass
        elif self.show_scores:
            pass
        else:
            """Respond to keypresses."""
            if event.key == pygame.K_RIGHT:
                self.ship.moving_right = True
            elif event.key == pygame.K_LEFT:
                self.ship.moving_left = True
            elif event.key == pygame.K_q:
                sys.exit()
            elif event.key == pygame.K_SPACE:
                self.ship.shoot()
                self.shoot_sound.play()

    def _check_keyup_events(self, event):
        if self.new_game:
            pass
        elif self.show_scores:
            pass
        else:
            """Respond to key releases."""
            if event.key == pygame.K_RIGHT:
                self.ship.moving_right = False
            elif event.key == pygame.K_LEFT:
                self.ship.moving_left = False

    def alien_hit(self):
        for bullet in self.ship.gun.bullet_list:
            for alien in self.fleet.fleet:
                if alien.rect.colliderect(bullet):
                    self.ship.score.add(alien.score)
                    self.ship.gun.remove(bullet)
                    self.fleet.fleet.remove(alien)
                    self.fleet.speedup()
                    break

    def saucer_hit(self):
        for bullet in self.ship.gun.bullet_list:
            if self.fleet.saucer.rect.colliderect(bullet):
                self.ship.score.add(
                    random.randint(self.settings.saucer_score_min,
                                   self.settings.saucer_score_max))
                self.ship.gun.remove(bullet)
                self.fleet.saucer.despawned = True

    def ship_hit(self):
        for bullet in self.fleet.gun.bullet_list:
            if self.ship.rect.colliderect(bullet):
                self.ship.life -= 1
                self.fleet.gun.remove(bullet)
            break

    def update(self):
        if self.new_game:
            pass
        elif self.show_scores:
            pass
        elif self.game_over:
            pass
        else:
            if len(self.fleet.fleet) == 0:
                self.ship.gun.reset()
                del self.fleet
                self.fleet = Fleet(self.settings)

            self.ship_hit()
            self.alien_hit()
            self.saucer_hit()
            self.fleet.out_of_bound(self.settings)
            self.fleet.move()
            self.ship.move()

    def draw(self):
        if self.new_game:
            self.scene.fill(self.settings.bg_color)
            self.start_screen.draw(self.scene, self.scene_count)
        elif self.show_scores:
            self.scene.fill(self.settings.bg_color)
            self.high_score_screen.draw()
        elif self.game_over:
            self.game_over_screen.draw()
        else:
            self.scene.fill(self.settings.bg_color)
            self.fleet.draw(self.scene, self.scene_count)
            self.ship.draw(self.scene, self.scene_count)
            self.ship.draw_life(self.scene, self.scene_count)

    def run_game(self):
        while True:
            self._check_events()
            self.update()
            self.draw()
            self.scene_count += 1

            if self.ship.life == 0:
                self.high_score_screen.save_score(self.ship.score.score)
                self.game_over = True

            pygame.display.update()
            time.sleep(0.1)
Esempio n. 2
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game."""
        # Initialize game display
        pygame.init()
        self.settings = Settings()
        if self.settings.fullscreen:
            self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
            self.settings.screen_width = self.screen.get_rect().width
            self.settings.screen_height = self.screen.get_rect().height
        else:
            self.screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        # Game is paused initiallly
        self.active = False

        # Initialize basic logic variables
        self.level = 1
        self.ships_remaining = self.settings.ship_limit

        # Initialize game elements
        self.player_ship = Ship(self)
        self.fleet = Fleet(self)
        self.play_button = Button(self, "Play")
        self.scoreboard = Scoreboard(self)

    def run(self):
        """Start the main game loop."""
        while True:
            # Check for keyboard/mouse events
            self._check_events()

            # Update player ship and alien fleet, if game is active
            if self.active:
                self.player_ship.update()
                self.fleet.update()

            # Draw the game
            self._draw()

    def _draw(self):
        """Draw the game screen and all elements."""

        # Redraw the background
        self.screen.fill(self.settings.bg_color)

        # Redraw the player ship
        self.player_ship.draw()

        # Redraw the alien fleet
        self.fleet.draw()

        # Redraw the scoreboard
        self.scoreboard.draw()

        # Redraw play button if game is inactive
        if not self.active:
            self.play_button.draw()

        # Make the most recently drawn screen visible
        pygame.display.flip()

    def _start_game(self):
        """Start a new game."""
        # Reset game
        self.level = 1
        self.ships_remaining = self.settings.ship_limit
        self.scoreboard.reset()
        self.settings.initialize_dynamic_settings()
        self.fleet = Fleet(self)
        self.player_ship.reset()

        # Hide cursor
        pygame.mouse.set_visible(False)

        # Start game
        self.active = True

    def kill_player(self):
        """Handle player death."""
        if self.ships_remaining > 0:
            # Decrement number of ships remaining
            self.ships_remaining -= 1
            self.scoreboard.reset()

            # Create new fleet and ship
            self.fleet = Fleet(self)
            self.player_ship.reset()

            # Pause
            sleep(0.5)
        else:
            self.active = False
            pygame.mouse.set_visible(True)

    def kill_alien(self):
        """Handle alien kills."""
        self.scoreboard.set_score(self.scoreboard.score +
                                  self.settings.alien_points)

        # Create a new fleet if all aliens are gone
        if not self.fleet.aliens:
            self.player_ship.reset()
            self.fleet = Fleet(self)
            # Increment speed (difficulty)
            self.settings.increase_speed()
            # Increment level
            self.level += 1
            self.scoreboard.prep_level()

    def _check_events(self):
        """Respond to keyboard and mouse events."""
        for event in pygame.event.get():
            # Exit when the game window is closed
            if event.type == pygame.QUIT:
                self.scoreboard.save_high_score()
                sys.exit()
            # Respond to mouse events
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            # Respond to key events
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_event(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_event(event)

    def _check_keydown_event(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            self.player_ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.player_ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            self.player_ship.fire_bullet()
        elif event.key == pygame.K_q:
            self.scoreboard.save_high_score()
            sys.exit()
        elif event.key == pygame.K_p and not self.active:
            self._start_game()

    def _check_keyup_event(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_RIGHT:
            self.player_ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.player_ship.moving_left = False

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.active:
            self._start_game()