精华内容
下载资源
问答
  • 出于这个想法,我便利用Python中的pygame库编写了一个关于外星人入侵游戏游戏说明如下: 在游戏外星人入侵》中,玩家控制着一艘最初出现在屏幕底部中央的飞船。玩家可以使用箭头键左右移动飞船,还可以使用...

    Python:《外星人入侵》
    现在地球科技发展的十分迅速,相信在不久的将来,人类一定能像游戏《第二银河》中那样在太空遨游。到了那时,外星文明会发现我们,战争也就无法避免了。

    出于这个想法,我便利用Python中的pygame库编写了一个关于外星人入侵的游戏,游戏说明如下:
    在游戏《外星人入侵》中,玩家控制着一艘最初出现在屏幕底部中央的飞船。玩家可以使用箭头键左右移动飞船,还可以使用空格键进行射击。游戏开始时,一群外星人出现在天空中,他们在屏幕中向下移动。玩家的任务就是射杀这些外星人。玩家将所有外星人都消灭干净以后,将会出现一群新的外星人,他们移动的速度更快。只要有外星人撞到了玩家的飞船或到达屏幕底部,玩家就损失一艘飞船。玩家损失三艘飞船后,游戏结束。

    话不多说,上代码:
    源代码如下:

    import pygame
    from pygame.sprite import Group
    
    from settings import Settings
    from game_stats import GameStats
    from scoreboard import Scoreboard
    from button import Button
    from ship import Ship
    import game_functions as gf
    
    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 = Button(ai_settings, screen, "Play")
        
        # Create an instance to store game statistics, and a scoreboard.
        stats = GameStats(ai_settings)
        sb = Scoreboard(ai_settings, screen, stats)
        
        # Set the background color.
        bg_color = (230, 230, 230)
        
        # 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)
    
        # Start the main loop for the game.
        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, screen, stats, sb, ship, aliens,
                    bullets)
            
            gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                bullets, play_button)
    
    run_game()
    

    辅助代码如下:

    import pygame
    from pygame.sprite import Group
    
    from settings import Settings
    from game_stats import GameStats
    from scoreboard import Scoreboard
    from button import Button
    from ship import Ship
    import game_functions as gf
    
    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 = Button(ai_settings, screen, "Play")
        
        # Create an instance to store game statistics, and a scoreboard.
        stats = GameStats(ai_settings)
        sb = Scoreboard(ai_settings, screen, stats)
        
        # Set the background color.
        bg_color = (230, 230, 230)
        
        # 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)
    
        # Start the main loop for the game.
        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, screen, stats, sb, ship, aliens,
                    bullets)
            
            gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                bullets, play_button)
    
    run_game()
    
    
    import pygame
    from pygame.sprite import Sprite
    
    class Bullet(Sprite):
        """A class to manage bullets fired from the ship."""
    
        def __init__(self, ai_settings, screen, ship):
            """Create a bullet object, at the ship's current position."""
            super(Bullet, self).__init__()
            self.screen = screen
    
            # Create bullet rect at (0, 0), then set correct position.
            self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
                ai_settings.bullet_height)
            self.rect.centerx = ship.rect.centerx
            self.rect.top = ship.rect.top
            
            # Store a decimal value for the bullet's position.
            self.y = float(self.rect.y)
    
            self.color = ai_settings.bullet_color
            self.speed_factor = ai_settings.bullet_speed_factor
    
        def update(self):
            """Move the bullet up the screen."""
            # Update the decimal position of the bullet.
            self.y -= self.speed_factor
            # Update the rect position.
            self.rect.y = self.y
    
        def draw_bullet(self):
            """Draw the bullet to the screen."""
            pygame.draw.rect(self.screen, self.color, self.rect)
    
    
    import pygame.font
    
    class Button():
    
        def __init__(self, ai_settings, screen, msg):
            """Initialize button attributes."""
            self.screen = screen
            self.screen_rect = screen.get_rect()
            
            # Set the dimensions and properties of the button.
            self.width, self.height = 200, 50
            self.button_color = (0, 255, 0)
            self.text_color = (255, 255, 255)
            self.font = pygame.font.SysFont(None, 48)
            
            # Build the button's rect object, and center it.
            self.rect = pygame.Rect(0, 0, self.width, self.height)
            self.rect.center = self.screen_rect.center
            
            # The button message only needs to be prepped once.
            self.prep_msg(msg)
    
        def prep_msg(self, msg):
            """Turn msg into a rendered image, and center text on the button."""
            self.msg_image = self.font.render(msg, True, self.text_color,
                self.button_color)
            self.msg_image_rect = self.msg_image.get_rect()
            self.msg_image_rect.center = self.rect.center
            
        def draw_button(self):
            # Draw blank button, then draw message.
            self.screen.fill(self.button_color, self.rect)
            self.screen.blit(self.msg_image, self.msg_image_rect)
    
    
    import sys
    from time import sleep
    
    import pygame
    
    from bullet import Bullet
    from alien import Alien
    
    def check_keydown_events(event, ai_settings, screen, ship, bullets):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            fire_bullet(ai_settings, screen, ship, bullets)
        elif event.key == pygame.K_q:
            sys.exit()
            
    def check_keyup_events(event, ship):
        """Respond to key releases."""
        if event.key == pygame.K_RIGHT:
            ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            ship.moving_left = False
    
    def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens,
            bullets):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                check_keydown_events(event, ai_settings, screen, ship, bullets)
            elif event.type == pygame.KEYUP:
                check_keyup_events(event, ship)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                check_play_button(ai_settings, screen, stats, sb, play_button,
                    ship, aliens, bullets, mouse_x, mouse_y)
                
    def check_play_button(ai_settings, screen, stats, sb, play_button, ship,
            aliens, bullets, mouse_x, mouse_y):
        """Start a new game when the player clicks Play."""
        button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
        if button_clicked and not stats.game_active:
            # Reset the game settings.
            ai_settings.initialize_dynamic_settings()
            
            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
            
            # Reset the game statistics.
            stats.reset_stats()
            stats.game_active = True
            
            # Reset the scoreboard images.
            sb.prep_score()
            sb.prep_high_score()
            sb.prep_level()
            sb.prep_ships()
            
            # Empty the list of aliens and bullets.
            aliens.empty()
            bullets.empty()
            
            # Create a new fleet and center the ship.
            create_fleet(ai_settings, screen, ship, aliens)
            ship.center_ship()
    
    def fire_bullet(ai_settings, screen, ship, bullets):
        """Fire a bullet, if limit not reached yet."""
        # Create a new bullet, add to bullets group.
        if len(bullets) < ai_settings.bullets_allowed:
            new_bullet = Bullet(ai_settings, screen, ship)
            bullets.add(new_bullet)
    
    def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
            play_button):
        """Update images on the screen, and flip to the new screen."""
        # Redraw the screen, each pass through the loop.
        screen.fill(ai_settings.bg_color)
        
        # Redraw all bullets, behind ship and aliens.
        for bullet in bullets.sprites():
            bullet.draw_bullet()
        ship.blitme()
        aliens.draw(screen)
        
        # Draw the score information.
        sb.show_score()
        
        # Draw the play button if the game is inactive.
        if not stats.game_active:
            play_button.draw_button()
    
        # Make the most recently drawn screen visible.
        pygame.display.flip()
        
    def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
        """Update position of bullets, and get rid of old bullets."""
        # Update bullet positions.
        bullets.update()
    
        # Get rid of bullets that have disappeared.
        for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                bullets.remove(bullet)
                
        check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship,
            aliens, bullets)
            
    def check_high_score(stats, sb):
        """Check to see if there's a new high score."""
        if stats.score > stats.high_score:
            stats.high_score = stats.score
            sb.prep_high_score()
                
    def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship,
            aliens, bullets):
        """Respond to bullet-alien collisions."""
        # Remove any bullets and aliens that have collided.
        collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
        
        if collisions:
            for aliens in collisions.values():
                stats.score += ai_settings.alien_points * len(aliens)
                sb.prep_score()
            check_high_score(stats, sb)
        
        if len(aliens) == 0:
            # If the entire fleet is destroyed, start a new level.
            bullets.empty()
            ai_settings.increase_speed()
            
            # Increase level.
            stats.level += 1
            sb.prep_level()
            
            create_fleet(ai_settings, screen, ship, aliens)
        
    def check_fleet_edges(ai_settings, aliens):
        """Respond appropriately if any aliens have reached an edge."""
        for alien in aliens.sprites():
            if alien.check_edges():
                change_fleet_direction(ai_settings, aliens)
                break
            
    def change_fleet_direction(ai_settings, aliens):
        """Drop the entire fleet, and change the fleet's direction."""
        for alien in aliens.sprites():
            alien.rect.y += ai_settings.fleet_drop_speed
        ai_settings.fleet_direction *= -1
        
    def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets):
        """Respond to ship being hit by alien."""
        if stats.ships_left > 0:
            # Decrement ships_left.
            stats.ships_left -= 1
            
            # Update scoreboard.
            sb.prep_ships()
            
        else:
            stats.game_active = False
            pygame.mouse.set_visible(True)
        
        # Empty the list of aliens and bullets.
        aliens.empty()
        bullets.empty()
        
        # Create a new fleet, and center the ship.
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()
        
        # Pause.
        sleep(0.5)
        
    def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens,
            bullets):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = screen.get_rect()
        for alien in aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
                break
                
    def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
        """
        Check if the fleet is at an edge,
          then update the postions of all aliens in the fleet.
        """
        check_fleet_edges(ai_settings, aliens)
        aliens.update()
        
        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(ship, aliens):
            ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
    
        # Look for aliens hitting the bottom of the screen.
        check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets)
                
    def get_number_aliens_x(ai_settings, alien_width):
        """Determine the number of aliens that fit in a row."""
        available_space_x = ai_settings.screen_width - 2 * alien_width
        number_aliens_x = int(available_space_x / (2 * alien_width))
        return number_aliens_x
        
    def get_number_rows(ai_settings, ship_height, alien_height):
        """Determine the number of rows of aliens that fit on the screen."""
        available_space_y = (ai_settings.screen_height -
                                (3 * alien_height) - ship_height)
        number_rows = int(available_space_y / (2 * alien_height))
        return number_rows
        
    def create_alien(ai_settings, screen, aliens, alien_number, row_number):
        """Create an alien, and place it in the row."""
        alien = Alien(ai_settings, screen)
        alien_width = alien.rect.width
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        aliens.add(alien)
    
    def create_fleet(ai_settings, screen, ship, aliens):
        """Create a full fleet of aliens."""
        # Create an alien, and find number of aliens in a row.
        alien = Alien(ai_settings, screen)
        number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
        number_rows = get_number_rows(ai_settings, ship.rect.height,
            alien.rect.height)
        
        # Create the fleet of aliens.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                create_alien(ai_settings, screen, aliens, alien_number,
                    row_number)
    
    
    class GameStats():
        """Track statistics for Alien Invasion."""
        
        def __init__(self, ai_settings):
            """Initialize statistics."""
            self.ai_settings = ai_settings
            self.reset_stats()
            
            # Start game in an inactive state.
            self.game_active = False
            
            # High score should never be reset.
            self.high_score = 0
            
        def reset_stats(self):
            """Initialize statistics that can change during the game."""
            self.ships_left = self.ai_settings.ship_limit
            self.score = 0
            self.level = 1
    
    
    import pygame.font
    from pygame.sprite import Group
    
    from ship import Ship
    
    class Scoreboard():
        """A class to report scoring information."""
    
        def __init__(self, ai_settings, screen, stats):
            """Initialize scorekeeping attributes."""
            self.screen = screen
            self.screen_rect = screen.get_rect()
            self.ai_settings = ai_settings
            self.stats = stats
            
            # Font settings for scoring information.
            self.text_color = (30, 30, 30)
            self.font = pygame.font.SysFont(None, 48)
    
            # Prepare the initial score images.
            self.prep_score()
            self.prep_high_score()
            self.prep_level()
            self.prep_ships()
    
        def prep_score(self):
            """Turn the score into a rendered image."""
            rounded_score = int(round(self.stats.score, -1))
            score_str = "{:,}".format(rounded_score)
            self.score_image = self.font.render(score_str, True, self.text_color,
                self.ai_settings.bg_color)
                
            # Display the score at the top right of the screen.
            self.score_rect = self.score_image.get_rect()
            self.score_rect.right = self.screen_rect.right - 20
            self.score_rect.top = 20
            
        def prep_high_score(self):
            """Turn the high score into a rendered image."""
            high_score = int(round(self.stats.high_score, -1))
            high_score_str = "{:,}".format(high_score)
            self.high_score_image = self.font.render(high_score_str, True,
                self.text_color, self.ai_settings.bg_color)
                    
            # Center the high score at the top of the screen.
            self.high_score_rect = self.high_score_image.get_rect()
            self.high_score_rect.centerx = self.screen_rect.centerx
            self.high_score_rect.top = self.score_rect.top
            
        def prep_level(self):
            """Turn the level into a rendered image."""
            self.level_image = self.font.render(str(self.stats.level), True,
                    self.text_color, self.ai_settings.bg_color)
            
            # Position the level below the score.
            self.level_rect = self.level_image.get_rect()
            self.level_rect.right = self.score_rect.right
            self.level_rect.top = self.score_rect.bottom + 10
            
        def prep_ships(self):
            """Show how many ships are left."""
            self.ships = Group()
            for ship_number in range(self.stats.ships_left):
                ship = Ship(self.ai_settings, self.screen)
                ship.rect.x = 10 + ship_number * ship.rect.width
                ship.rect.y = 10
                self.ships.add(ship)
            
        def show_score(self):
            """Draw score to the screen."""
            self.screen.blit(self.score_image, self.score_rect)
            self.screen.blit(self.high_score_image, self.high_score_rect)
            self.screen.blit(self.level_image, self.level_rect)
            # Draw ships.
            self.ships.draw(self.screen)
    
    
    class Settings():
        """A class to store all settings for Alien Invasion."""
    
        def __init__(self):
            """Initialize the game's static settings."""
            # Screen settings.
            self.screen_width = 1200
            self.screen_height = 800
            self.bg_color = (230, 230, 230)
            
            # Ship settings.
            self.ship_limit = 3
                
            # Bullet settings.
            self.bullet_width = 3
            self.bullet_height = 15
            self.bullet_color = 60, 60, 60
            self.bullets_allowed = 3
            
            # Alien settings.
            self.fleet_drop_speed = 10
                
            # How quickly the game speeds up.
            self.speedup_scale = 1.1
            # How quickly the alien point values increase.
            self.score_scale = 1.5
        
            self.initialize_dynamic_settings()
    
        def initialize_dynamic_settings(self):
            """Initialize settings that change throughout the game."""
            self.ship_speed_factor = 1.5
            self.bullet_speed_factor = 3
            self.alien_speed_factor = 1
            
            # Scoring.
            self.alien_points = 50
        
            # fleet_direction of 1 represents right, -1 represents left.
            self.fleet_direction = 1
            
        def increase_speed(self):
            """Increase speed settings and alien point values."""
            self.ship_speed_factor *= self.speedup_scale
            self.bullet_speed_factor *= self.speedup_scale
            self.alien_speed_factor *= self.speedup_scale
            
            self.alien_points = int(self.alien_points * self.score_scale)
    
    
    import pygame
    from pygame.sprite import Sprite
    
    class Ship(Sprite):
    
        def __init__(self, ai_settings, screen):
            """Initialize the ship, and set its starting position."""
            super(Ship, self).__init__()
            self.screen = screen
            self.ai_settings = ai_settings
    
            # Load the ship image, and get its rect.
            self.image = pygame.image.load('images/ship.bmp')
            self.rect = self.image.get_rect()
            self.screen_rect = screen.get_rect()
    
            # Start each new ship at the bottom center of the screen.
            self.rect.centerx = self.screen_rect.centerx
            self.rect.bottom = self.screen_rect.bottom
            
            # Store a decimal value for the ship's center.
            self.center = float(self.rect.centerx)
            
            # Movement flags.
            self.moving_right = False
            self.moving_left = False
            
        def center_ship(self):
            """Center the ship on the screen."""
            self.center = self.screen_rect.centerx
            
        def update(self):
            """Update the ship's position, based on movement flags."""
            # Update the ship's center value, not the rect.
            if self.moving_right and self.rect.right < self.screen_rect.right:
                self.center += self.ai_settings.ship_speed_factor
            if self.moving_left and self.rect.left > 0:
                self.center -= self.ai_settings.ship_speed_factor
                
            # Update rect object from self.center.
            self.rect.centerx = self.center
    
        def blitme(self):
            """Draw the ship at its current location."""
            self.screen.blit(self.image, self.rect)
    
    

    飞船图片和外星人图片如下:
    在这里插入图片描述
    在这里插入图片描述
    游戏截图如下:
    在这里插入图片描述
    在这里插入图片描述

    展开全文
  • python项目 外星人入侵

    2018-04-12 22:00:31
    python从入门到精通》的一个项目,外星人入侵,配置完Python 3.0环境后可直接运行
  • 一款Python制作的游戏,是<Python编程:从入门到实践>中的一个项目. 游戏运行需安装Pygame,运行游戏请打开文件"alien_invasion.py". 另:因为游戏为文件夹形式,经过压缩后上传,请下载者自行下载解压软件进行解压.
  • Python小游戏源码-外星人入侵游戏源码
  • 外星人入侵Python

    2018-05-24 00:30:07
    该压缩包里面是完整的用Python语言编写的《外星人入侵小游戏的程序代码,程序开发环境win10+python3.6 ,亲测可运行。
  • 外星人入侵(python).rar

    2019-10-01 14:12:12
    外星人入侵,一个小游戏,根据书本源代码编写,增加了上下移动的功能,初学Python的同学可以拿去试试练练手。
  • 一个简单的外星人入侵小游戏,玩家操纵飞船进行射击,消灭外星飞船并计分。利用pygame进行的游戏项目开发。
  • 我是按照买的资料书上来做的,在我代码里面呢,增加了一些资料上没有的功能,比如说外星人是随机产生的(资料书是创建整个外星人群),本来打算让每个外星人随机移动的,但是试了一下发现,外星人移动杂乱无章,然后...

    作者:weixin_wangyanpi 

    https://blog.csdn.net/weixin_44412311/article/details/106590762


    历时七天,终于做出来了(因为还要上网课,学习其他的东西,所以做的比较慢,如果每天能拿出五个小时做这个游戏的话,个人觉得三天差不多,当然了,这是对于小白来说)。我是按照买的资料书上来做的,在我代码里面呢,增加了一些资料上没有的功能,比如说外星人是随机产生的(资料书是创建整个外星人群),本来打算让每个外星人随机移动的,但是试了一下发现,外星人移动杂乱无章,然后后就采用了资料书上的做法,让它们作为整体移动;还有就是在射中外星人的时候,可能会产生暴击(emmm,其实是福利吧,bone,不是说伤害有暴击,这个“暴击”得分会更高一些);再一个就是随着等级增加,飞船发射子弹的宽度以及每次发射子弹的数量都会有所增加,当然,外星人以及飞船移动速度也会增加;再一个就是最高分(High score)、当前分数(score)、飞船剩余生命、等级(level)的布局和资料书有所不同,改动就大致这些吧,以后还会逐渐改善,比如增加声音啊,让外星人也能发射子弹,飞船碰到外星人的子弹也会死亡之类的功能吧。OK,废话少说,下面上代码!

    alien_invasion.py:

    """该游戏主程序,尽量做到最简单"""
    import pygame
    
    
    from settings import Settings
    from ship import Ship
    from pygame.sprite import Group
    from game_stats import GameStats
    from button import Button
    from score_board import Scoreboard
    
    
    import game_function as gf
    
    
    def run_game():
           """初始化背景设置"""
           pygame.init()
           
           """"创建一个Settings实例"""
           ai_settings=Settings()
           
           """创建一个游戏窗口以及标题"""
           screen=pygame.display.set_mode(
                  (ai_settings.screen_width,ai_settings.screen_height))
           pygame.display.set_caption('Alien Invasion')
           
           """创建一艘飞船实例"""
           ship=Ship(ai_settings,screen)
           
           """创建一个用于存储子弹和外星人的编组"""
           bullets=Group()
           aliens=Group()
    
    
           """创建外星人群"""
           gf.creat_fleet(ai_settings,screen,ship,aliens)
    
    
           """创建存储游戏统计信息的实例,并创建记分牌"""
           stats = GameStats(ai_settings)
           sb = Scoreboard(ai_settings,screen,stats)
           
           #创建play按钮
           play_button = Button(ai_settings,screen,"Play")
           
           """进入主循环"""  
           while True:
                  """"监视用户的操作,键盘和鼠标"""
                  gf.check_events(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb)
                  if stats.game_active:
                         """更新飞船"""
                         ship.update()
                         """更新子弹"""
                         gf.update_bullet(ai_settings,screen,ship,aliens,bullets,stats,sb)
                         """更新外星人"""
                         gf.update_aliens(ai_settings,screen,ship,aliens,stats,bullets,sb)
                  """刷新屏幕"""
                  gf.update_screen(ai_settings,screen,ship,aliens,bullets,
                                   stats,play_button,sb)
    
    
    run_game()
    

    game_function.py:
    如果把这个游戏比作一个人,那么上一段代码是刚接触这个人,他给你留下的第一印象,那么下面这段代码可以说是这个人的灵魂了

    import sys
    import pygame
    
    
    from random import randint
    from bullet import Bullet
    from alien import Alien
    from time import sleep
    
    
    def fire_bullet(ai_settings,screen,ship,bullets,stats):
           """开火!"""
           #确保屏幕上的子弹数在限制范围内
           for i in range(int(stats.level/5) + 1):
                  if len(bullets) < ai_settings.bullet_allowed:
                         new_bullet=Bullet(ai_settings,screen,ship)
                         bullets.add(new_bullet)
    
    
    def check_keydown(event,ai_settings,screen,ship,bullets,stats):
           """检查用户按键是否按下以及执行的任务"""
           if event.key  == pygame.K_RIGHT:
                  ship.moving_right=True
                                
           elif event.key == pygame.K_LEFT:
                  ship.moving_left=True
    
    
           elif event.key == pygame.K_UP:
                  ship.moving_up=True
    
    
           elif event.key == pygame.K_DOWN:
                  ship.moving_down=True
    
    
           elif event.key == pygame.K_SPACE:
                  #发射一颗子弹,并且在限制范围内
                  fire_bullet(ai_settings,screen,ship,bullets,stats)
                  
    def check_keyup(event,ship):
           """检查用户释放按键"""
           if event.key == pygame.K_RIGHT:
                  ship.moving_right=False
                                
           elif event.key == pygame.K_LEFT:
                  ship.moving_left=False
    
    
           elif event.key == pygame.K_UP:
                  ship.moving_up=False
    
    
           elif event.key == pygame.K_DOWN:
                  ship.moving_down=False
        
    
    def check_events(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb):
           """响应键盘和鼠标事件"""
           for event in pygame.event.get():
                  if event.type == pygame.K_q:
                         sys.exit()
                  #如果一直按下右键或者左键,空格键,则向右或右移动或者开火       
                  elif event.type == pygame.KEYDOWN:
                         check_keydown(event,ai_settings,screen,ship,bullets,stats)
                  
                  #释放右键或左键,停止移动
                  elif event.type == pygame.KEYUP:
                         check_keyup(event,ship)
    
    
                  #点击Play按钮,开始游戏
                  elif event.type == pygame.MOUSEBUTTONDOWN:
                         mouse_x,mouse_y = pygame.mouse.get_pos()
                         check_play_button(ai_settings,screen,ship,aliens,bullets,
                           stats,play_button,mouse_x,mouse_y,sb)
                  
    def  check_play_button(ai_settings,screen,ship,aliens,bullets,
                           stats,play_button,mouse_x,mouse_y,sb):
           """在玩家单击Play按钮时开始游戏"""
           button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
           if button_clicked and not stats.game_active:
                  #重置游戏设置
                  ai_settings.init_dynamic_settings()
                  #隐藏光标
                  pygame.mouse.set_visible(False)
                  #重置游戏统计信息
                  stats.reset_stats()
                  stats.game_active = True
    
    
                  #重置记分牌图像
                  sb.prep_score()
                  sb.prep_high_score(screen)
                  sb.prep_level()
                  sb.prep_ships(screen)
    
    
                  #清空外星人和子弹列表
                  aliens.empty()
                  bullets.empty()
    
    
                  #创建一群新的外星人,并让飞船居中
                  creat_fleet(ai_settings,screen,ship,aliens)
                  ship.center_ship(ai_settings)
                                                                            
    def update_screen(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb):
           """每次循环都重绘屏幕"""
           screen.fill(ai_settings.bg_color)
           for bullet in bullets.sprites():
                  bullet.draw_bullet()
           ship.blitme()
           aliens.draw(screen)
           sb.show_score()
           
           #如果游戏处于非活动状态,绘制Play按钮
           if not stats.game_active:
                  play_button.draw_button()
                  
           """"刷新屏幕,擦去旧屏幕,显示新屏幕"""
           pygame.display.flip()
    
    
    
    def update_bullet(ai_settings,screen,ship,aliens,bullets,stats,sb):
           """更新子弹位置,并删除已经消失的子弹"""
           #更新子弹位置
           bullets.update()
           #删除消失的子弹
           for bullet in bullets.copy():
                  if bullet.rect.bottom<=0:
                         bullets.remove(bullet)
           #检查是否有子弹击中外星人
           check_bullet_alien_colide(ai_settings,screen,ship,aliens,bullets,stats,sb)
           
    def get_number_aliens_x(ai_settings,alien_width):
           """获得水平方向上外星人个数"""
           available_space_x = ai_settings.screen_width-2 * alien_width
           number_aliens_x = int(available_space_x/(2 * alien_width))
           return number_aliens_x
    
    
    def get_space_rows(ai_settings,ship_height,alien_height):
           """获得垂直方向上外星人的行数"""
           available_space_y = (ai_settings.screen_height-(3 * alien_height)-
                              ship_height)                            
           number_aliens_rows = int(available_space_y/(2 * alien_height))
           return number_aliens_rows
    
    
    def creat_alien(ai_settings,screen,aliens,alien_number,row_number):
           """根据传入的数据在某个位置创建一个外星人"""
           alien = Alien(ai_settings,screen)
           alien_width = alien.rect.width
           alien.x = alien_width + 2 * alien_width * alien_number
           alien.rect.x = alien.x
           alien.rect.y = (alien.rect.height +20) + 2 * alien.rect.height * row_number 
           aliens.add(alien)
    
    
    def creat_random_alien_x(number_aliens_x,ai_settings,screen,aliens,row_number):
           """在第一行随机创建若干个外星人"""
           for i in range(2,number_aliens_x+2):
                  random_number_x=randint(2,i)
                  for alien_number in range(random_number_x - 1,random_number_x):
                         creat_alien(ai_settings,screen,aliens,alien_number,row_number)
                         
    
    def creat_fleet(ai_settings,screen,ship,aliens):
           """创建外星人群以及获取屏幕上最大的行数和每行最多个数"""
           alien=Alien(ai_settings,screen)
           number_aliens_x = get_number_aliens_x(ai_settings,alien.rect.width)
           number_rows = get_space_rows(ai_settings,ship.rect.height,
                                        alien.rect.height)
           """随机创建行数"""
           for j in range(0,number_rows):
                  random_number_y = randint(0,j)
                  for row_number in range(random_number_y):
                         creat_random_alien_x(number_aliens_x,ai_settings,
                                                     screen,aliens,row_number)
    
    
    def check_fleet_edges(ai_settings,aliens):
           """有外星人到达屏幕边缘"""
           for alien in aliens.sprites():
                  if alien.check_edges():
                         change_fleet_direction(ai_settings,aliens)
                         break
                  
    def change_fleet_direction(ai_settings,aliens):
           """将外星人下移,并改变它们的方向"""
           for alien in aliens.sprites():
                  alien.rect.y += ai_settings.fleet_drop_speed
           ai_settings.fleet_direction *= -1
           
    def update_aliens(ai_settings,screen,ship,aliens,stats,bullets,sb):
           """检测有外星人位于屏幕边缘或者相撞或者外星人到达底部,更新外星人的位置"""       
           check_fleet_edges(ai_settings,aliens)
           aliens.update()
    
    
           #检测飞船与外星人的撞击
           if pygame.sprite.spritecollideany(ship,aliens):
                  ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb)
           #检查是否有外星人到达屏幕底部
           check_aliens_bottom(ai_settings,screen,ship,aliens,stats,bullets,sb)
    
    
    def check_bullet_alien_colide(ai_settings,screen,ship,aliens,bullets,stats,sb):
           """检测子弹和外星人的碰撞"""
           collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)
           #两个True可使得子弹与外星人碰撞后消失,并返回一个字典
           #碰撞之后加分
           if collisions:
                  for aliens in collisions.values():
                         i = randint(0,10)
                         if i>8:
                                stats.score += (ai_settings.alien_points + 10) * len(aliens)
                                sb.prep_score()
                         else:
                                stats.score += ai_settings.alien_points * len(aliens)
                                sb.prep_score()
                  #检查是否刷新最高分
                  check_high_score(stats,sb,screen)
                  
           if len(aliens) == 0:
                  #删除现有的子弹,加快游戏速度,创建新的外星人
                  ship.center_ship(ai_settings)
                  bullets.empty()
                  ai_settings.increase_speed()
                  #提高等级
                  stats.level += 1
                  ai_settings.increase_bullet_size()
                  sb.prep_level()
                  
                  creat_fleet(ai_settings,screen,ship,aliens)
    
    
    
    def ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb):
           """飞船与外星人相撞,生命减1,清除外星人和子弹列表
           并创建新的外星人,飞船放在屏幕底部中央位置"""
           if stats.ship_left > 0:
                  stats.ship_left -= 1
                  sb.prep_ships(screen)
                  #清空外星人和子弹列表
                  aliens.empty()
                  bullets.empty()
                  #新建一个飞船和外星人群
                  creat_fleet(ai_settings,screen,ship,aliens)
                  ship.center_ship(ai_settings)
                  #暂停0.5秒
                  sleep(0.5)
           else:
                  ai_settings.bullet_width = 3 
                  stats.game_active = False
                  pygame.mouse.set_visible(True)
                 
    def check_aliens_bottom(ai_settings,screen,ship,aliens,stats,bullets,sb):
           """检查是否有外星人到达底部"""
           screen_rect = screen.get_rect()
           for alien in aliens.sprites():
                  if alien.rect.bottom >= screen_rect.bottom:
                       ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb)
                       break
           
    def check_high_score(stats,sb,screen):
           """检查是否产生了新的最高分"""
           if stats.score > stats.high_score:
                  stats.high_score = stats.score
                  sb.prep_high_score(screen)
    

    后面的文件基本是作为分支吧,一些属性还有一些初始化的数据,都是为game_function文件提供资源的

    settings.py:

    class Settings():
           def __init__(self):
                  """设置长度和宽度以及背景色属性"""
                  self.screen_width = 800
                  self.screen_height = 700
                  self.bg_color=(255,255,255)
                  self.ship_limit = 2
    
    
                  """子弹设置""" 
                  self.bullet_width = 3
                  self.bullet_height=15
                  self.bullet_color=(60,60,60)
                  self.bullet_allowed=8
    
    
                  """外星人移动设置"""
                  self.fleet_drop_speed = 10
                  """以什么样的速度加快游戏节奏"""
                  self.speed_up_scale = 1.1
                  self.init_dynamic_settings()
    
    
                  """外星人点数的提高"""
                  self.score_scale = 1.5
    
    
                  """子弹大小提高"""
                  self.bullet_scale = 10
    
    
           def init_dynamic_settings(self):
                  self.speed = 1.5
                  self.bullet_speed = 3
                  self.alien_speed = 0.2
                  #fleet_direction为1表示向右移动,-1表示向左移动
                  self.fleet_direction = -1
    
    
                  #计分
                  self.alien_points = 10
    
    
           def increase_speed(self):
                  """提高速度设置和外星人点数设置"""
                  self.speed *= self.speed_up_scale
                  self.bullet_speed *= self.speed_up_scale
                  self.alien_speed *= self.speed_up_scale
    
    
                  self.alien_points = int(self.alien_points * self.score_scale)
    
    
           def increase_bullet_size(self):
                  self.bullet_width += self.bullet_scale
    

    ship.py:

    import pygame
    
    
    from pygame.sprite import Sprite
    
    
    class Ship(Sprite):
           def __init__(self,ai_settings,screen):
                  """初始化飞船并设置其初始位置"""
                  super(Ship,self).__init__()
                  self.screen=screen
    
    
                  #加载飞船图像并获取其外接矩形
                  self.image=pygame.image.load('images/ship.bmp')
                  self.rect=self.image.get_rect()#获取飞船的矩形
                  self.screen_rect=screen.get_rect()#获取屏幕矩形
    
    
                  self.ai_settings=ai_settings
    
    
                  #将每艘新飞船放在屏幕底部中央位置
                  self.rect.centerx=self.screen_rect.centerx
                  self.rect.centery=self.screen_rect.centery
                  self.rect.bottom=self.screen_rect.bottom
    
    
                  self.center_x=float(self.rect.centerx)
                  self.center_y=float(self.rect.centery)
                  """连续检测按键,设置未按下右键为False"""
                  self.moving_right=False
                  self.moving_left=False
                  self.moving_up=False
                  self.moving_down=False
    
    
           def update(self):
                  """如果连续按方向键,则一直移动,并且不超过边界"""
                  if self.moving_right and self.rect.right < self.screen_rect.right:
                         self.center_x+=self.ai_settings.speed
                         
                 #使用两个if,这样玩家同时按下两个键,
                 #将先增大rect.centerx值,再降低,则飞船位置不变       
                  if self.moving_left and self.rect.left > 0:
                         self.center_x-=self.ai_settings.speed
    
    
                  if self.moving_up and self.rect.top > 0:
                         self.center_y-=self.ai_settings.speed
                         
                  if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
                         self.center_y+=self.ai_settings.speed
    
    
                  self.rect.centerx=self.center_x
                  self.rect.centery=self.center_y
                  
           """在指定位置绘制飞船"""
           def blitme(self):
                  self.screen.blit(self.image,self.rect)
    
    
           def center_ship(self,ai_settings):
                  self.center_x = ai_settings.screen_width/2
                  self.center_y = ai_settings.screen_height - 28
    

    alien.py:

    import pygame
    from pygame.sprite import Sprite
    
    
    class Alien(Sprite):
           def __init__(self,ai_settings,screen):
                  super().__init__()
                  """初始化外星人并设置其初始位置"""
                  self.screen=screen
                  self.ai_settings=ai_settings
    
    
                  #加载外星人图像并设置rect属性
                  self.image=pygame.image.load('images/alien.bmp')
                  self.rect=self.image.get_rect()
    
    
                  #每个外星人都在屏幕左上角附近
                  self.rect.x=self.rect.width
                  self.rect.y=self.rect.height 
    
    
                  #存储外星人准确位置
                  self.x=float(self.rect.x)
    
    
           def check_edges(self):
                  """如果外星人碰到屏幕边缘,则返回True"""
                  screen_rect = self.screen.get_rect()
                  if self.rect.right >= screen_rect.right:
                         return True
                  elif self.rect.left <= 0:
                         return True
    
    
           def update(self):
                  """移动外星人"""
                  self.x += (self.ai_settings.alien_speed *
                             (self.ai_settings.fleet_direction))
                  self.rect.x=self.x
    
    
           def blitme(self):
                  """在指定位置绘制飞船"""
                  self.screen.blit(self.image,self.rect)
    

    bullet.py:

    import pygame
    from pygame.sprite import Sprite
    
    
    class Bullet(Sprite):
           def __init__(self,ai_settings,screen,ship):
                  #在飞船位置创建一个子弹对象
                  super(Bullet,self).__init__()
                  self.screen=screen
    
    
                  self.rect=pygame.Rect(0,0,ai_settings.bullet_width
                                        ,ai_settings.bullet_height)
                  self.rect.centerx = ship.rect.centerx
                  self.rect.top = ship.rect.top
                  self.y=float(self.rect.y)
                  self.color=ai_settings.bullet_color
                  self.speed=ai_settings.bullet_speed
    
    
           def update(self):
                  """向上移动子弹"""
                  #更新子弹的小数值
                  self.y -= self.speed
                  self.rect.y=self.y
    
    
           def draw_bullet(self):
                  """在屏幕上绘制子弹"""
                  pygame.draw.rect(self.screen,self.color,self.rect)
    

    button.py:

    import pygame.font
    
    
    class Button():
           def __init__(self,ai_settings,screen,msg):
                  """初始化按钮属性"""
                  self.screen = screen
                  self.screen_rect = screen.get_rect()
    
    
                  #设置按钮大小以及其他属性
                  self.width,self.height = 200,50
                  self.button_color = (0, 255, 0)
                  self.text_color = (60,60,60)
                  self.font = pygame.font.SysFont(None,48)
    
    
                  #创建按钮的rect对象,并使其居中
                  self.rect = pygame.Rect(0, 0, self.width, self.height)
                  self.rect.center = self.screen_rect.center
    
    
                  #按钮的标签只需要创建一次
                  self.prep_msg(msg)
    
    
           def prep_msg(self,msg):
                  """将msg渲染为图像,并使其在按钮上居中"""
                  self.msg_image = self.font.render(msg,True,self.text_color,
                                                     self.button_color)
                  self.msg_image_rect = self.msg_image.get_rect()
                  self.msg_image_rect.center = self.rect.center
    
    
           def draw_button(self):
                  #绘制一个用颜色填充的按钮,再绘制文本
                  self.screen.fill(self.button_color,self.rect)
                  self.screen.blit(self.msg_image,self.msg_image_rect)
    

    game_stats.py:

    class GameStats():
           """跟踪游戏的统计信息"""
           def __init__(self,ai_settings):
                  self.ai_settings = ai_settings
                  self.game_active = False
                  self.reset_stats()
    
    
                  #任何情况下都不能重置最高分
                  self.high_score = 0
    
    
           def reset_stats(self):
                  """初始化在游戏运行过程中可能变化的统计信息"""
                  self.ship_left = self.ai_settings.ship_limit
                  self.score = 0
                  self.level = 1
                  self.bullet_width = 3
    

    scord_board.py:

    import pygame.font
    
    
    from pygame.sprite import Group
    from ship import Ship
    
    
    class Scoreboard():
           """显示得分的类"""
           def __init__(self,ai_settings,screen,stats):
                  """初始化显示得分的属性"""
                  self.screen = screen
                  self.screen_rect = screen.get_rect()
                  self.ai_settings = ai_settings
                  self.stats = stats
    
    
                  #显示得分时的字体设置
                  self.text_color = (30,30,30)
                  self.font = pygame.font.SysFont(None,48)
    
    
                  #准备初始得分图像以及当前最高得分
                  self.prep_score()
                  self.prep_high_score(screen)
                  self.prep_level()
                  self.prep_ships(screen)
    
    
           def prep_score(self):
                  """将得分转化为可渲染的图像"""
                  rounded_score = int(round(self.stats.score,-1))
                  score_str ="Score:"+"{:,}".format(rounded_score)
                  self.score_image = self.font.render(score_str,True,self.text_color,
                                                      self.ai_settings.bg_color)
    
    
                  #将得分放在屏幕右上角
                  self.score_rect = self.score_image.get_rect()
                  self.score_rect.right = self.screen_rect.right - 20
                  self.score_rect.top = 20
    
    
           def prep_high_score(self,screen):
                  """将最高得分渲染为图片"""
                  high_score = int(round(self.stats.high_score,-1))
                  high_score_str = "High Score:"+"{:,}".format(high_score)
                  self.high_score_image = self.font.render(high_score_str,True,self.text_color,
                                                      self.ai_settings.bg_color)
    
    
                  """将最高得分放在屏幕左上角"""
                  self.high_score_rect = self.high_score_image.get_rect()
                  self.high_score_rect.left = self.screen_rect.left + 20
                  self.high_score_rect.top = 20
    
    
           def prep_level(self):
                  """将等级渲染为图像"""
                  self.level_image = self.font.render("Level:"+str(self.stats.level),True,
                                                      self.text_color,self.ai_settings.bg_color)
    
    
                  #将等级放在右下角
                  self.level_rect = self.level_image.get_rect()
                  self.level_rect.right = self.score_rect.right
                  self.level_rect.bottom = self.score_rect.bottom + 650
    
    
           def show_score(self):
                  """在屏幕上显示得分,最高分,等级"""
                  self.screen.blit(self.score_image,self.score_rect)
                  self.screen.blit(self.high_score_image,self.high_score_rect)
                  self.screen.blit(self.level_image,self.level_rect)
                  #绘制剩余飞船
                  self.ships.draw(self.screen)
    
    
           def prep_ships(self,screen):
                  """显示剩余的飞机"""
                  self.ships = Group()
                  for ship_number in range(self.stats.ship_left + 1):
                         ship =Ship(self.ai_settings,self.screen)
                         ship.rect.x = 10 + ship_number * ship.rect.width
                         ship.rect.y = self.screen_rect.top + 640
                         self.ships.add(ship)
    

    代码的话,我觉得注释已经比较清楚了,然后就没有多费口舌去解释

    下面是运行之后的截图:

    当三艘飞船用光后,结束游戏

    再次点击“Play”按钮,再次开始

    上面就是代码还有运行之后的照片了,虽然游戏到目前为止还不是很完善,但是这七天我真的学会了很多东西,我觉得对我最有益的还是学会了模块化思维,这种思维就是将复杂的问题分解成小的模块,如果这些小的模块仍然比较麻烦,那就继续分解,说实话,短短七天,这种思想已经开始渗透到其他的学科,甚至我的日常生活,想到这我还是非常开心的。还有的话就是学会了类,学会了类的属性以及方法,还有大范围的使用函数(在game_function文件中可以看到,单这个文件就大概用了15到20个函数),大大提高了我使用函数的熟练度。

    emmm,在大一开始学习C语言,那时候也不听课,上C语言就看那些游戏主播,然后做题也不会,考试的时候背了几段代码就去考试了,结果还做出来了8个(总共11个,没有选择填空这些理论题目),那时候就暗下发誓,这辈子永远不会去学这些编程语言!!!现在,嚯~!真香啊!我再次接触C语言是因为要学习单片机,要参加比赛,然后不得不去复习,然后慢慢的发现,C语言是这么的简单啊(当然,学到指针那地方也是让我头疼了好几个周,还有后面的数据结构也是),然后慢慢的又开始接触上了Python,一开始是看B站小甲鱼的视频学习,但是慢慢地,感觉没有资料完全听不懂,所以呢,又买了以恶不能资料书去学习,本来打算看视频然后配合视频学习的,但是后来发现,小甲鱼的视频其实更偏向于python进阶,所以就放弃了视频,主攻资料书了。

    总的来说吧,对于自己现在的状态非常满意,嘿嘿!

    分享或在看是对我最大的支持 

    展开全文
  • 主要为大家详细介绍了Python外星人入侵游戏编程完整的实现思路,具有一定的参考价值,感兴趣的伙伴们可以参考一下
  • Python知识的练习,也可以作为一个简单的游戏来玩,在学习之余动动手,可以提高学习兴趣
  • 打包好的pygame经典入门小游戏外星人入侵原始1.0版本的文件,包括py文件和图片文件,运行alien_invasion即可。 其中alien是专门写外星人的,alien_invasion是主程序,bullet是控制子弹及相关参数的,button是控制...
  • 关注公众号:Python学习指南,回复“外星人”即可获取 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可。 原理介绍 游戏简介: 玩家通过鼠标控制飞船行动和射击,若能在敌人到达游戏界面底端之前...

    开发工具

    Python版本:3.6.4

    相关模块:

    pygame模块;

    以及一些Python自带的模块。

    相关文件

    关注公众号:Python学习指南,回复“外星人”即可获取

    环境搭建

    安装Python并添加到环境变量,pip安装需要的相关模块即可。

    原理介绍

    游戏简介:

    玩家通过鼠标控制飞船行动和射击,若能在敌人到达游戏界面底端之前消灭所有敌人,则游戏胜利,否则游戏失败。

    逐步实现:

    Step1:定义游戏精灵类

    首先,我们来明确一下游戏需要哪些角色。

    ① 我方飞船

    我方飞船通过鼠标控制,其需要具备射击、移动和被敌人击中后爆炸等能力。

    因此,该游戏精灵类的代码实现如下:

    图片

    ② 敌人

    敌人由电脑自动控制,其需要具备射击、移动和被我方击中后爆炸等能力。

    因此,该游戏精灵类的代码实现如下:

    图片

    ③ UFO

    UFO由电脑控制,可以看作是彩蛋,击中这个彩蛋,你将获得大量的奖励分数,当奖励分数累积到一定量时,你将获得额外的生命值奖励。

    UFO类只需要具备移动和被我方击中后爆炸的能力即可。

    因此,该游戏精灵类的代码实现如下:

    图片

    ④ 子弹类

    我方飞船和敌人射击时都需要用到子弹,其应当具备不断向前移动的能力。

    我方子弹类的代码实现如下:

    image.gif

    敌方子弹类的代码实现如下:

    图片

    Step2:实现游戏主循环

    先初始化,包括加载必要的游戏素材和实例化之前定义的游戏精灵类等等:

    图片

    然后就可以进入游戏主循环啦~

    首先是按键检测,来实现用户与游戏的交互:

    图片

    接下来就是根据用户操作的结果以及电脑自动进行的操作获得的结果来实现游戏画面更新。当然,更新之前需要根据游戏规则对一些游戏精灵进行碰撞检测,包括:敌方子弹和我方飞船以及我方子弹和敌方等。

    具体的代码实现如下:

    图片

    最后就是把一些游戏相关的数据实时显示在游戏界面上以供玩家参考:

    图片

    Step3:定义游戏结束界面

    我们只需要根据玩家是否取得了游戏胜利来展示游戏结束界面即可:

    图片

    All Done!完整源代码欢迎与我进行交流。

    展开全文
  • 这里说一下为什么会我会遇到这问题:首先,我从书本《python编程:从入门到实践》上学到了这个《外星人入侵》(实则就是飞机大战)小游戏的编写(看着书本写的,自己来的话还真不一定能复述出来),这个过程还是挺...

    问题引出:

    提示:没有生成exe经验的朋友可以先看一下我之前写的相关文章
    python文件生成exe之在pycharm使用pyinstaller指令

    这里说一下为什么会我会遇到这问题:首先,我从书本《python编程:从入门到实践》上学到了这个《外星人入侵》(实则就是飞机大战)小游戏的编写(看着书本写的,自己来的话还真不一定能复述出来),这个过程还是挺有趣的。
    所以我还是想把这个分享给别人,不过不能直接把代码发过去吧,所以我就想着把它弄成exe文件,随后直接发个压缩包就解决了,但是就在我想着直接来一句pyinstaller -F 文件名.py,结果不然,问题见下:


    问题描述:

    我的exe文件是在目录下生成了的,随后我把图片文件加入了exe的那个文件目录下,运行exe。
    一个黑框很体面的出来了,它就只有这设定的窗口名字,随后等待了几秒就说了一句“再见”。完蛋,这就得开始我的排错过程了。
    `


    解决过程:

    提示:这里我的解决过程,敬请过目:
    我是第一次生成多文件得exe程序,所以我先把问题归在这里了:

    pyinstaller -F -w alien_invasion2.py -p alien.py -p alien_bullet.py -p bullet.py -p button.py -p game_function.py -p game_stats.py -p scorabroad.py -p settings.py -p ship.py
    

    这段老长了。检查了好几次没有出错(第一个py文件要是你这个项目的主文件)。
    好的,多试了几次我就放弃了这个,既然多文件生成有问题的话,来试一下单个文件的exe吧。于是十个文件被我合并为了一个py文件(当然,得要是对的)。

    再来一次,有生成了一波exe文件,再重复一下基本过程,打开它,还是一个黑框,一现就没了。

    问题出在哪呢?接下来我开始在CSDN上找一下答案,看一下是不是自己弄错了什么。接着看到一个博客上说了一点:程序里面设置的字体不要使用none型的,改成任意一个你电脑自带的字体。
    好的,我改!
    在这里插入图片描述
    在这里插入图片描述
    就是单纯改变了字体,然后我再次来到了生成exe的这一步。
    在这里插入图片描述
    上图一出,我的exe文件再次生成了,满怀激动的打开dist文件夹,图片一添加就运行程序。
    这次不负众望,运行出来了:
    在这里插入图片描述
    紧接着怎么办?点赞啊,你的支持是我最大的动力!


    展开全文
  • 点击上方“Python爬虫与数据挖掘”,进行关注回复“书籍”即可获赠Python从入门到进阶共10本电子书今日鸡汤为学应须毕生力,攀高贵在少年时。大家好,我是白纯。这是我在【Python...
  • Python游戏开发–外星人入侵游戏(一) 在本文中,我将尝试去进行自己的第一个项目,该项目将完全参考埃里克·马瑟斯先生的著作进行编写,在此对埃里克·马瑟斯先生表示由衷的谢意。 创建游戏是趣学语言的...
  • PYTHON游戏编程外星人入侵的完整实现思路,具体内容如下准备工作:下载python,比如Anaconda3(64 bit),导入pygame游戏包1.外星人设置,alien.py,代码:import pygamefrom pygame.sprite import Spriteclass ...
  • python实现外星人入侵小游戏前言一、alien_invasion.py二、game_function.py三、settings.py四、bullet.py五、alien_bullet.py六、ship.py七、alien.py八、button.py九、socrebroad.py十、game_stats.py总结 ...
  • python小游戏外星人入侵》,源码下载,包括矢量图和代码部分。
  • pygame小游戏外星人入侵(alien_invasion);里面代码图片资源包齐全,代码有注释,可直接运行
  • 这篇文章主要为大家详细介绍了Python外星人入侵游戏编程完整的实现思路文中示例代码介绍的非常详细具 有一 的参考价值感兴趣的伙伴们可以参考一下 PYTHON游戏编程外星人入侵的完整实现思路具体内容如下 ...
  • 往期回顾 Python实现经典吃豆豆小游戏 Python实现“小兔子和Bun”游戏 Python实现八音符小游戏 Python实现拼图小游戏 Python实现滑雪小游戏 ...今天给大家分享外星人入侵小游戏让我们愉快地开始吧 开发
  • stats.score+= ai_settings.alien_points *len(aliens) sb.prep_score() check_high_score(stats,sb)if len(aliens)==0:#删除现有的子弹并新建一群外星人,加快游戏进度节奏 bullets.empty() ai_settings.increase_...
  • python外星人入侵游戏开发)

    万次阅读 2019-06-06 13:12:58
    大二下小学期《“python从入门到实践”》,看到外星人入侵小项目那部分兴致大增,遂决定自己也来写一个。 python外星人入侵游戏开发) 外星人游戏添加飞船上下移动功能: 功能源代码: 以上代码是在game_...
  • Python项目 外星人入侵游戏

    千次阅读 多人点赞 2020-07-16 12:28:43
    游戏外星人入侵》中,玩家控制着一艘最初出现在屏幕底部中央的飞船。玩家可以使用箭头键左右移动飞船,还可使用空格键进行射击。游戏开始时,一群外星人出现在天空中,他们在屏幕中向下移动。玩家的任务是射杀...
  • 距离上次贴出《python编程:从入门到实践》13.1-14.1章的代码已经过了又有半个月,这里给大家亲测可用的13.1-14.3的全部代码。具体的代码可能会和书上的稍有不同,主要是计分环节的前面加了“highest”、“current”...
  • 在学习了Python后进行实战是最好的熟练方法,最近在学习外星人入侵小游戏的程序,分享在这里和大家进行交流。 我将分几次将程序分享完,今天首先分享一下游戏的主程序,游戏的主程序中调用其他的块和函数,来完成...
  • python外星人入侵游戏

    万次阅读 多人点赞 2018-06-25 15:10:50
    本文内容是使用pygame包来开发一款python2D游戏,类似于我们小时候玩的飞机大战,飞船发射子弹biubiubiu~~然后外星人就消灭了,并且每消灭一群外星人后,玩家都将提高一个等级,随着等级提高游戏节奏也会加快。...
  • python游戏外星人入侵

    2018-08-06 13:05:25
    python的pygame做的项目游戏外星人入侵,飞船发射子弹消灭外星人
  • python项目《外星人入侵》增加上下操作 目的: 可以上下移动 确保上下不会过界 ship.py(新增y轴存储,飞船移动及上下边界): import pygame class Ship(): def __init__(self,ai_settings,screen): '''初始化...
  • 看别人玩你写的游戏能获得满足感,而编写简单的游戏有助于你明白专业级游戏是怎样编写出来的。 提示:以下是本篇文章正文内容,下面案例可供参考 一、pandas是什么? 示例:pandas 是基于NumPy 的一种工具,该工具...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 995
精华内容 398
关键字:

python小游戏外星人入侵

python 订阅