def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        # Get game's settings
        self.settings = Settings()

        # Create a main display
        self.screen = pygame.display.set_mode((1200, 800))

        # Set a main display's name
        pygame.display.set_caption("Space Battle")

        # Create an instance to store game statistics
        self.stats = GameStats(self)

        # Create a scoreboard
        self.scoreboard = Scoreboard(self)

        # Create a rocket
        self.rocket = Rocket(self)

        # Create a list of bullets
        self.bullets = pygame.sprite.Group()

        # Create a fleet of spaceships
        self.spaceships = pygame.sprite.Group()
        self._create_fleet()

        # Make the Start button.
        self.start_button = PlayButton(self, "Start")
    def __init__(self):
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.shooter = Shooter(self)
        self.lines = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.bulletbs = pygame.sprite.Group()
        self.balls = pygame.sprite.Group()
        self.ball2s = pygame.sprite.Group()

        self._create_fleet()
        self._create_fleet2()

        # Make the play button.
        self.play_button = PlayButton(self, "Right wheel to play")

        # Make the Settings button.
        self.settings_button = SettingsButton(self, "Settings")

        # Make the setttings menu.
        self.settings_menu = SettingsMenu(self, "fast or slow press y or n")

        # Make the speed button.
        self.speed_button = SpeedButton(self, "you have selected the fast option")

        # Make the second speed button.
        self.speed_button2 = SpeedButton2(self, "You have selected the slower options")
Example #3
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    # 屏幕宽高
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("外星人入侵")
    # 创建开始按钮
    play_button = PlayButton(ai_settings, screen, "Play")
    # 创建一艘飞船
    ship = Ship(ai_settings, screen)
    # 创建一个用于存储子弹的编组
    bullets = Group()
    # 创建一个外星人
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # 存储游戏统计信息的实例
    stats = GameStats(ai_settings)
    # 实例化记分类
    sb = Scoreboard(ai_settings, screen, stats)
    # 开始游戏的主循环
    while True:
        # 监听键盘和鼠标事件
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Example #4
0
    def run_game():
        # Initialize game and create a screen object.
        pygame.init()
        settings = Settings()
        screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
        pygame.display.set_caption("Domesday")

        # Make the play button.
        play_button = PlayButton(screen, "PLAY")

        # Create an instance to store game statistics and create scoreboard.
        stats = GameStats(settings)
        sb = Scoreboard(settings, screen, stats)

        # Make a spaceship, a group of bullets and a group of aliens.
        spaceship = SpaceShip(settings, screen)
        bullets = Group()
        aliens = Group()

        # Create the fleet of aliens.
        gf = GameFunctions()
        gf.create_fleet(settings, screen, spaceship, aliens)

        # Start the main loop for the game.
        while True:
            gf.check_events(settings, screen, stats, sb, play_button, spaceship, aliens, bullets)

            if stats.game_active:
                spaceship.update()
                # bullets.update() -> to-do old version of updating bullets.
                # Get rid of bullets that have disappeared.
                gf.update_bullets(settings, screen, stats, sb, spaceship, aliens, bullets)
                gf.update_aliens(settings, screen, stats, sb, spaceship, aliens, bullets)

            gf.update_screen(settings, screen, stats, sb, spaceship, aliens, bullets, play_button)
def run_game():

    # Initialise game, settings, and screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make play button
    play_button = PlayButton(screen, "PLAY")

    # Make a ship
    ship = Ship(screen, ai_settings)

    # Creating fleet of aliens
    aliens = Group()
    gf.create_fleet(aliens, ai_settings, screen, ship)

    # Make a group of bullets
    bullets = Group()

    # Creating GameStats
    game_stats = GameStats(ai_settings)

    # Creating Score Board Instance
    scoreboard = Scoreboard(screen, game_stats, ai_settings)

    # Start the main loop for the game
    while True:

        gf.check_events(ship, screen, ai_settings, bullets, game_stats,
                        play_button, aliens, scoreboard)
        if game_stats.game_active:

            ship.update()
            gf.update_bullets(bullets, aliens, ai_settings, screen, ship,
                              game_stats, scoreboard)
            gf.update_aliens(aliens, ai_settings, ship, bullets, screen,
                             game_stats, scoreboard)

        gf.update_screen(screen, ship, ai_settings, bullets, aliens,
                         play_button, game_stats, scoreboard)
def run_game():
    #initialize game and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #Make play button
    play_button = PlayButton(ai_settings, screen, "Play")

    #Make ship
    ship = Ship(ai_settings, screen)

    #Create an instance to store gane stats
    stats = GameStats(ai_settings)
    scoreboard = Scoreboard(ai_settings, screen, stats, ship)

    #Create fleet of aliens
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #Make a group to store bullets
    bullets = Group()

    while True:
        gf.check_events(ai_settings, screen, ship, aliens, play_button, stats,
                        bullets, scoreboard)

        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, aliens, ai_settings, stats, screen,
                              scoreboard, ship)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets,
                             scoreboard)

        gf.update_screen(ai_settings, screen, stats, scoreboard, ship, aliens,
                         bullets, play_button)
Example #7
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    
    # Make the Play button.
    play_button = PlayButton(ai_settings, screen, "Play")
    
    # Make the Help button.
    help_button = HelpButton(ai_settings, screen, "Help")
    
    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    
    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    
    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens, stats)
    
    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, help_button)
        
        if stats.game_active == True:
            ship.update()
            gf.update_bullets(ai_settings, stats, screen, sb, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)
            
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, 
                         play_button, help_button)
class SidewaysShooter:

    def __init__(self):
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.shooter = Shooter(self)
        self.lines = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.bulletbs = pygame.sprite.Group()
        self.balls = pygame.sprite.Group()
        self.ball2s = pygame.sprite.Group()

        self._create_fleet()
        self._create_fleet2()

        # Make the play button.
        self.play_button = PlayButton(self, "Right wheel to play")

        # Make the Settings button.
        self.settings_button = SettingsButton(self, "Settings")

        # Make the setttings menu.
        self.settings_menu = SettingsMenu(self, "fast or slow press y or n")

        # Make the speed button.
        self.speed_button = SpeedButton(self, "you have selected the fast option")

        # Make the second speed button.
        self.speed_button2 = SpeedButton2(self, "You have selected the slower options")
        
    def run_game(self):
        """Start the main game loop."""
        Running, Pause = 0, 1
        state = Running
        while True:
            self._check_events()
            if self.stats.game_active:
                self._check_events()
                self.shooter.update()
                self._update_bullets()
                self._update_shooter()
                self.check_if_empty()
                

                        
            self._update_screen()

    def _check_events(self):
        LEFT = 1
        MIDDLE = 2
        RIGHT = 3
        """Respond to keypresses and mouse events."""
        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 and event.button == LEFT:
                #mouse_pos2 = pygame.mouse.get_pos()
                #self._check_play_button(mouse_pos2)
                #None
                self._fire_bullet()

            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == MIDDLE:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
                #pause
                
                #self._check_settings_button(mouse_pos)

            #elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos2 = pygame.mouse.get_pos()
                self.settings_button.flag = True
                #self._check_settings_button(mouse_pos2)
                
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == RIGHT:
                #mouse_pos = pygame.mouse.get_pos()
                #self._check_play_button(mouse_pos) 
                self._fire_bulletb()
                
    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.stats.game_active:
            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_shooters()

            # Get rid of any remaining balss and aliens
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()
            self.shooter3()

            # Create a new fleet.
            self._create_fleet()
            self._create_fleet2()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
        

    def _check_settings_button(self, mouse_pos2):
        """load the settings when the player clicks settings"""
        if self.settings_button.rect.collidepoint(mouse_pos2):
            #self.settings_button.flag = True
            #self.settings_menu.check_image()
            self.settings_menu.draw_button()

    
        
                        
    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_x:
            self.shooter.moving_right = True
        elif event.key == pygame.K_c:
            self.shooter.moving_left = True
        elif event.key == pygame.K_SPACE:
            self._fire_line()
        elif event.key == pygame.K_RIGHT:
            self.settings_button.flag = True
            #self.speed_button.draw_button()
        elif event.key == pygame.K_LEFT:
            self.settings_button.flag = False
            self.settings_menu.draw_button()
            pygame.mouse.set_visible(True)
        elif event.key == pygame.K_y:
            self.speed_button.flag2 = True
            while self.speed_button.flag2 == True:
                self.speed_button2.flag3 = False
                break
            self.settings.shooter_speed2 = 0.09
        elif event.key == pygame.K_n:
            self.speed_button2.flag3 = True
            while self.speed_button2.flag3 == True:
                self.speed_button.flag2 = False
                break
            self.settings.shooter_speed2 = 0.01
        elif event.key == pygame.K_p:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
            self.settings_button.flag = False
            #self.settings_button()
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()
            self.shooter3()
            self._create_fleet()
            self._create_fleet2()
        elif event.key == pygame.K_q:
            pygame.mouse.set_visible(True)
            sys.exit()

    def shooter3(self):
        self.shooter = Shooter(self)

    def check_if_empty(self):
        if len(self.balls) == 0 and len(self.ball2s) == 0:
            pass

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_x:
            self.shooter.moving_right = False
        elif event.key == pygame.K_c:
            self.shooter.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _fire_bulletb(self):
        """Create a new bullet and add it to the group."""
        if len(self.bulletbs) < self.settings.bulletbs_allowed:
            new_bulletb = Bulletb(self)
            self.bulletbs.add(new_bulletb)

    def _update_bullets(self):
        """Update position of bullerts and get rid of old bullets."""
        # Update bullet positions
        self.bullets.update()
        self.bulletbs.update()
        self.lines.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.right >= self.settings.screen_width:
                self.bullets.remove(bullet)

        for bulletb in self.bulletbs.copy():
            if bulletb.rect.right >= self.settings.screen_width:
                self.bulletbs.remove(bulletb)

        self._check_bullet_ball_collisions()
        
    def _check_bullet_ball_collisions(self):
        """Respond to bullet-ball collisions."""
        # Remove any bullets and balls that have collided.
        # Check for any bullets that have hit any balls
        #  If so, get rid of the bullets and the ball
        collisions = pygame.sprite.groupcollide(self.bullets, self.balls, True, True)
        collisions2 = pygame.sprite.groupcollide(self.bulletbs, self.ball2s, True, True)
        collisions3 = pygame.sprite.groupcollide(self.lines, self.balls, True, True)
        collisions4 = pygame.sprite.groupcollide(self.lines, self.ball2s, True, True)

        if collisions3 or collisions4 == True:
            self._shooter_hit()

        if collisions:
            for balls in collisions.values():
                self.stats.score += self.settings.ball_points * len(balls)
            self.sb.prep_score()
            self.sb.check_high_score()
            
        if collisions2:
            for ball2s in collisions2.values():
                self.stats.score += self.settings.ball_points2 * len(ball2s)
            self.sb.prep_score()
            self.sb.check_high_score()

            
    def _update_shooter(self):
        """Update the position of the shooter."""
        self.shooter.update()

        # Look for ball-shooter collisions.
        if pygame.sprite.spritecollideany(self.shooter, self.balls):
            self._shooter_hit()

        if pygame.sprite.spritecollideany(self.shooter, self.ball2s):
            self._shooter_hit()

    
    def _shooter_hit(self):
        """Respond to the shooter being hit."""
        if self.stats.shooters_left > 0:
            # Decrement ships_left, and update scoreboard.
            self.stats.shooters_left -= 1
            self.sb.prep_shooters()

            # Get rid of any remaining balls and bullets.
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()

            # Create a new fleet
            self.shooter3()
            self._create_fleet()
            self._create_fleet2()

            # Pause.
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
                
    def _create_fleet(self):
        """Create the fleet of balls."""
        # Create a ball and find the number of balls in one row.
        # Spacing between ball is equal to one balls width.
        ball = Ball(self)
        ball_width = ball.rect.height
        ball_width, ball_height = ball.rect.size
        available_space_x = self.settings.screen_width 
        number_balls_x = available_space_x // (6 * ball_width)
 
        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.shooter.rect.height
        available_space_y = self.settings.screen_height 
        number_rows = available_space_y // (2 * ball_height)
        
        # Create the first fleet of aliens.
        for row_number in range(number_rows):
            for ball_number in range(number_balls_x):
                # Create a ball and place it in the row.
                ball = Ball(self)
                ball_width, ball_height = ball.rect.size
                ball.y = 2 * ball_width + (5 * ball_width * ball_number) 
                ball.rect.y = ball.y
                ball.rect.x =  19 *  ball_width  + (2 * ball_width * row_number) 
                self.balls.add(ball)

    def _create_fleet2(self):
        """Create the fleet of ball2s."""
        # Create a yellow ball and find the number of balls in a row.
        # Spacing between each ball is equal to one ball width.
        ball2 = Ball2(self)
        ball_width2 = ball2.rect.height
        ball_width2, ball_height2  = ball2.rect.size
        available_space_x2 = self.settings.screen_width
        number_ball2s_x = available_space_x2 // (6 * ball_width2)

        # Determine the number of balls that fit on the screen
        shooter_height = self.shooter.rect.height
        available_space_y2 = self.settings.screen_width
        number_rows2 = available_space_y2 // (2 * ball_height2)

        # Create the first fleet of balls.
        for row_number2 in range(number_rows2):
            for ball2_number in range(number_ball2s_x):
                # Create a ball and place it in the row.
                ball2 = Ball2(self)
                ball_width2, ball_height2 = ball2.rect.size
                ball2.y =  5 * ball_width2 * ball2_number
                ball2.rect.y = ball2.y
                ball2.rect.x =  19 * ball_width2 + (2 * ball_width2 * row_number2)
                self.ball2s.add(ball2)

    def _fire_line(self):
        """Create a new line and add it to the lines group."""
        for i in range(1):
            new_line = Line(self)
            self.lines.add(new_line)

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
         # Draw the play button if the game is inactive.
        #if not self.stats.game_active:
            #self.play_button.draw_button()
            
        self.screen.fill(self.settings.bg_color)
        self.shooter.blitme()
        #self._fire_line()
        
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
            

        for bulletb in self.bulletbs.sprites():
            bulletb.draw_bulletb()

        for line in self.lines.sprites():
            #self._fire_line()
            line.draw_line()
            
            
        self.balls.draw(self.screen)
        self.ball2s.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Draw the settings if the game is inactive.
        if not self.stats.game_active:
            self.settings_button.draw_button()

        if self.settings_button.flag == True and not self.stats.game_active:
            #self.settings_menu.check_image()
            self.settings_menu.draw_button()

        if self.speed_button.flag2 == True and not self.stats.game_active:
            self.speed_button2.flag3 = False
            self.speed_button.draw_button3()
            
            

        if self.speed_button2.flag3 == True and not self.stats.game_active:
            self.speed_button.flag2 = False
            self.speed_button2.draw_button4()
            
            

        #self.speed_button2.flag3 = False
        #self.speed_button.flag2 = False
            
        pygame.display.flip()
class SpaceBattle:
    """Main class that manages game's assets"""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        # Get game's settings
        self.settings = Settings()

        # Create a main display
        self.screen = pygame.display.set_mode((1200, 800))

        # Set a main display's name
        pygame.display.set_caption("Space Battle")

        # Create an instance to store game statistics
        self.stats = GameStats(self)

        # Create a scoreboard
        self.scoreboard = Scoreboard(self)

        # Create a rocket
        self.rocket = Rocket(self)

        # Create a list of bullets
        self.bullets = pygame.sprite.Group()

        # Create a fleet of spaceships
        self.spaceships = pygame.sprite.Group()
        self._create_fleet()

        # Make the Start button.
        self.start_button = PlayButton(self, "Start")

    def run_game(self):
        """Start game's main loop."""
        while True:
            # Monitors key presses and releases
            self._check_key_mouse_events()

            # Updates positions of game's moving elements
            self._update_positions()

            # Flipping the main screen
            self._update_screen()

    def _update_positions(self):
        """Update the position of a rocket, bullets, and spaceships."""
        if self.stats.game_active:
            self.rocket.update()
            self._update_bullets()
            self._update_spaceships()

    def _check_key_mouse_events(self):
        """Respond to key presses and mouse events."""
        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._press_play_button(mouse_pos)

    def _press_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""

        # Returns true if the point of a mouse click overlaps
        # with the start button
        button_clicked = self.start_button.rect.collidepoint(mouse_pos)

        # If the button is clicked and the game has not started yet,
        # it means player starts a new game. So, reset the game.
        if button_clicked and not self.stats.game_active:
            self._reset_dynamic_settings()
            self._reset_games_stats()

            # Get rid of any remaining spaceships
            self.spaceships.empty()

            # Get rid of any remaining bullets
            self.bullets.empty()
            
            # Create a new fleet
            self._create_fleet()

            # Center the rocket
            self.rocket.center_rocket()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _reset_games_stats(self):
        """Reset the game statistics."""
        self.stats.reset_stats()
        self.stats.game_active = True
        self.scoreboard.set_score()
        self.scoreboard.set_level()
        self.scoreboard.set_rockets()

    def _reset_dynamic_settings(self):
        """Reset the game's dynamic settings."""
        self.settings.initialize_dynamic_settings()

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            self.rocket.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.rocket.moving_left = True
        elif event.key == pygame.K_UP:
            self.rocket.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.rocket.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_RIGHT:
            self.rocket.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.rocket.moving_left = False
        elif event.key == pygame.K_UP:
            self.rocket.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.rocket.moving_down = False

    def _fire_bullet(self):
        """
        If the number of current bullets on the screen
        is less than number of bullets allowed to be fired, then
        create a new bullet and add it to the bullets group.
        """
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        self._clean_off_screen_bullets()

        self._check_bullet_spaceship_collisions()

    def _clean_off_screen_bullets(self):
        """Get rid of bullets that are off screen."""
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

    def _check_bullet_spaceship_collisions(self):
        """Respond to bullet-spaceship collisions."""

        # Returns dictionary containing bullets (key) and spaceships (values) that
        # were hit
        collisions = pygame.sprite.groupcollide(
                self.bullets, self.spaceships, True, True)

        self._update_total_score(collisions)

        self._increase_difficulty()

    def _increase_difficulty(self):
        """
        If there are no more spaceships on the screen, the
        increase the difficulty of the game
        """
        if not self.spaceships:
            # Destroy existing bullets and create new fleet.
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level.
            self.stats.level += 1
            self.scoreboard.set_level()

    def _update_total_score(self, collisions):
        """Update the total score on the game's screen"""
        # If collision dictionary exists, then add spaceships' total value to
        # a score.
        if collisions:
            for spaceships in collisions.values():
                self.stats.score += self.settings.spaceship_points * len(spaceships)

            # Create new image of updated total score
            self.scoreboard.set_score()
            self.scoreboard.check_high_score()

    def _update_spaceships(self):
        """
        Check if the fleet is at an border of a screen,
          then update the positions of spaceships' fleet.
        """
        self._check_fleet_edges()
        self.spaceships.update()

        # If the rocket touches an spaceship, then rocket is hit
        if pygame.sprite.spritecollideany(self.rocket, self.spaceships):
            self._rocket_hit()

        self._check_spaceships_bottom()

    def _check_spaceships_bottom(self):
        """Check if any spaceships have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for spaceship in self.spaceships.sprites():
            if spaceship.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the rocket got hit.
                self._rocket_hit()
                break

    def _rocket_hit(self):
        """Respond to the rocket being hit by an spaceship."""
        if self.stats.rockets_left > 0:
            # Decrement rockets_left, and update scoreboard.
            self.stats.rockets_left -= 1
            self.scoreboard.set_rockets()
            
            # Get rid of any remaining spaceships and bullets.
            self.spaceships.empty()
            self.bullets.empty()
            
            # Create a new fleet and center the rocket.
            self._create_fleet()
            self.rocket.center_rocket()
            
            # Pause a game to let player see what happened
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        """Create the fleet of spaceships."""

        # Create an spaceship and find the number of spaceships in a row.
        # Spacing between each spaceship is equal to one spaceship width.
        spaceship = SpaceShip(self)
        spaceship_width, spaceship_height = spaceship.rect.size

        # Calculate the number of spaceships in a row
        # (2 * spaceship_width) creates margins on either side of a screen
        available_space_x = self.settings.screen_width - (2 * spaceship_width)
        number_spaceships_x = available_space_x // (2 * spaceship_width)
        
        # Determine the number of rows of spaceships that fit on the screen.
        rocket_height = self.rocket.rect.height
        available_space_y = (self.settings.screen_height -
                                (18 * spaceship_height) - rocket_height)
        number_rows = available_space_y // (2 * spaceship_height)
        
        # Create the full fleet of spaceships.
        for row_number in range(number_rows):
            for spaceship_number in range(number_spaceships_x):
                self._create_spaceship(spaceship_number, row_number)

    def _create_spaceship(self, spaceship_number, row_number):
        """Create an spaceship and place it in the row."""
        spaceship = SpaceShip(self)
        spaceship_width, spaceship_height = spaceship.rect.size
        spaceship.x = spaceship_width + 2 * spaceship_width * spaceship_number
        spaceship.rect.x = spaceship.x
        spaceship.rect.y = 3.5 * spaceship.rect.height + 2 * spaceship.rect.height * row_number
        self.spaceships.add(spaceship)

    def _check_fleet_edges(self):
        """
        If any spaceship touches screen's edges,
        then change the direction of a fleet.
        """
        for spaceship in self.spaceships.sprites():
            if spaceship.check_edges():
                self._change_fleet_direction()
                break
            
    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for spaceship in self.spaceships.sprites():
            spaceship.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)

        # Draw a rocket
        self.rocket.blitme()

        # Draw bullets
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        # Draw spaceships
        self.spaceships.draw(self.screen)

        # Draw the score information.
        self.scoreboard.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.start_button.draw_button()

        pygame.display.flip()
Example #10
0
def run_game():
    pygame.init()
    game_settings = Settings()
    restored_settings = Settings()

    screen = pygame.display.set_mode(
        (game_settings.screen_length, game_settings.screen_height))
    pygame.display.set_caption("Catch It!")
    screen.fill((0, 160, 220))

    # Create basket object
    basket = Basket(screen, game_settings)

    # Create ball object, generate position, draw starting position
    ball = Ball(game_settings, screen, basket)
    ball.generate_random_pos()
    ball.draw_ball()
    bullets = Group()

    # Create spoiled fruit object, generate position, draw starting position
    spoiled_fruits = Group()
    spoiled_fruit = SpoiledFruit(game_settings, screen, basket)
    spoiled_fruits.add(spoiled_fruit)
    spoiled_fruit.generate_random_pos()
    spoiled_fruit.draw_ball()

    powerup = Powerup(game_settings, screen)

    # Create clock object to measure fps
    clock = pygame.time.Clock(
    )  # This creates a Clock object that is used to track time, with the other methods that come along with it.
    pygame.font.init()  # Initializes font module
    fps_font = pygame.font.Font(
        None, 30
    )  # This creates a new font object that we will use to display the fps. 'None' just tells it to use the default pygame font, 30 is font size.
    fps_constant = 150

    lives_font = pygame.font.Font(None, 30)
    play_button = PlayButton(screen, game_settings, 'Play!', 50,
                             game_settings.screen_height / 2)
    play_again_button = PlayButton(screen, game_settings, 'Play Again', 50,
                                   game_settings.screen_height - 200)
    play_button.draw_button()
    pygame.display.flip()

    # Score for how many good fruits are caught.
    score = pygame.font.Font(None, 50)

    # Pause text when game is paused
    pause = pygame.font.Font(None, 100)

    while True:
        gf.check_events(basket, bullets, screen, game_settings,
                        restored_settings, play_button, play_again_button,
                        spoiled_fruits, ball, pause)
        if game_settings.game_active == False:
            clock.tick()

        if game_settings.game_active:

            gf.check_spoiledfruit_collisions(ball, basket, game_settings,
                                             screen, spoiled_fruit, bullets,
                                             spoiled_fruits)

            gf.check_other_collisions(game_settings, screen, basket, ball,
                                      spoiled_fruits, powerup)

            gf.check_powerup_collisions(game_settings, screen, powerup, basket,
                                        bullets)

            gf.check_game_assist(game_settings, ball, spoiled_fruits)

            gf.update_screen(screen, game_settings, basket, ball, clock,
                             fps_font, lives_font, bullets, spoiled_fruit,
                             spoiled_fruits, play_button, play_again_button,
                             powerup, score, fps_constant)
        else:
            pygame.display.flip()