当前位置: 萬仟网 > IT编程>脚本编程>Python > 【学习笔记】大三集中实训在课堂完成一个基于python之外星人入侵小游戏

【学习笔记】大三集中实训在课堂完成一个基于python之外星人入侵小游戏

2020年11月19日  | 萬仟网IT编程  | 我要评论
由于没有什么经验只能跟着书本,一步一步完成调试,在这过程中又遇到很多错误都一一克服啦,在此记录一下学习笔记项目结构一、环境搭建安装pygame模块自行百度!!二、外星人设计入侵小游戏游戏介绍1.游戏《外星人入侵》的描述: 在游戏《外星人入侵》中,玩家控制着一艘最初出现在屏幕底部中央的飞船。玩家可以使用箭头键左右移动飞船,还可使用空格键进行射击。游戏开始时,一群外星 人出现在天空中,他们在屏幕中向下移动。玩家的任务是射杀这些外星人。玩家将所有外星人都消灭干净后,将出现一群新的外星人,他们移.

由于没有什么经验只能跟着书本,一步一步完成调试,在这过程中又遇到很多错误都一一克服啦,在此记录一下学习笔记

项目结构

1.目录
在这里插入图片描述2. 总体分为四部分

在这里插入图片描述

一、环境搭建

安装pygame模块

自行百度!!

二、外星人设计

入侵小游戏游戏介绍

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

编写alien_invasion.py模块

import pygame
import game_functions as gf
from settings import Settings
from ship import Ship

def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()   # 初始化背景设置,让pygame能正常工作

    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)   # 实例化一个飞船类,传入了参数ai_settings和屏幕对象screen

    # 开始游戏的主循环
    while True:
        gf.check_events(ship)  # 用于响应游戏事件

        ship.update()   # 更新飞船状态
        gf.update_screen(ai_settings, screen, ship)  # 重绘screen

run_game()

创建Settings.py类

class Settings:
    """存储《外星人入侵》的所有设置的类"""

    def __init__(self):
        """初始化游戏的设置"""
        # 屏幕设置
        self.screen_width = 1200   # 游戏窗口宽度
        self.screen_height = 800   # 游戏窗口高度
        self.bg_color = (230, 230, 230)  # 游戏背景颜色
        self.ship_speed_factor = 1.5  # 飞船的移动速度

创建Ship.py类

import pygame
class Ship:
    def __init__(self, ai_settings, screen): 


        """初始化飞机并设置其初始位置"""
        self.screen = screen
        self.ai_settings = ai_settings
        # 加载飞机图片并获取其外接矩形
        self.image = pygame.image.load("images/ship.bmp")
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        # 将每艘新飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
        # 自定义一个能存储浮点数的临时变量,x坐标
        self.center = float(self.rect.centerx)
        # 标志,用于表示是否正在向某个方向移动
        self.moving_right = False
        self.moving_left = False
    def update(self):
        """根据移动标志调整飞船的位置"""
        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
        # 用临时变量更新rect的centerx,截取截取整数部分
        self.rect.centerx = self.center
    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

注:
self.moving_right和self.moving_left标志,用于表示飞船是否正在移动,用于实现飞船在不松开按键下连续移动。
udpate()方法,用于增减飞船的中心位置x坐标(因为飞船只能在底部移动,所以不用改y坐标),并防止飞船移动出游戏窗口。
重写了blitme()函数,用于绘制飞船

创建 game_functions.py模块

import sys
import pygame
def check_keydown_event(event, ship):
    """响应按下按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    if event.key == pygame.K_LEFT:
        ship.moving_left = True 
def check_keyup_event(event, ship):
    """响应松开按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False

def check_events(ship):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_event(event, ship)

        elif event.type == pygame.KEYUP:
            check_keyup_event(event, ship)

def update_screen(ai_settings, screen, ship):
    """更新屏幕上的图像,并切换到新屏幕"""
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    ship.blitme()

    # 让最近绘制的屏幕可见
    pygame.display.flip()

注:
在pygame中,用K_RIGHT,K_LEFT表示方向按键,其实键盘上每个键在pygame中都有所对于,以K_开头。check_keydown_event()函数和check_keyup_event()函数都是对下面的check_event()的进一步简化,这两个函数的代码均可以放在check_event()中,但这样代码将会很臃肿,结构不清晰

添加射击功能

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):  # 使用精灵
    """一个对飞船发射的子弹进行管理的类"""

    def __init__(self, ai_settings, screen, ship):
        """在飞船所处的位置创建一个子弹对象"""
        super(Bullet, self).__init__()
        self.screen = screen

        # 在(0,0)处创建一个表示子弹的矩形,再设置正确的位置
        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           # 从飞机的顶部射出

        # 存储用浮点数表示的子弹位置,因为子弹只在y轴上运动,所以不需要x坐标
        self.y = float(self.rect.y)

        self.color = ai_settings.bullet_color   # 子弹颜色
        self.speed_factor = ai_settings.bullet_speed_factor   # 子弹速度

    def update(self):
        """向上移动子弹"""
        # 更新表示子弹位置的浮点数值
        self.y -= self.speed_factor
        # 更新表示子弹的rect的位置
        self.rect.y = self.y

    def draw_bullet(self):
        """在屏幕上绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)

三、 创建外星人

编写一个外星人Alien类

import pygame
from pygame.sprite import Sprite

class Alien(Sprite):
    """表示单个外星人的类"""
    def __init__(self, ai_settings, screen):
        """初始化外星人并设置其起始位置"""
        super(Alien, self).__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 blitme(self):
        """在指定位置绘制外星人"""
        self.screen.blit(self.image, self.rect)

改game_functions.py模块

def create_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_number_rows(ai_settings, ship.rect.height,
                                  alien.rect.height) 

    # 嵌套循环创建外星舰队
    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)

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 create_alien(ai_settings, screen, aliens, alien_number, row_number):
    """创建一个外星人并将其放在当前行"""
    alien = Alien(ai_settings, screen)
    # 下面就是根据上面的公式计算每一个外星人在窗口中的位置(这是左上角的坐标)
    alien.x = alien.rect.width * (1 + 2 * alien_number)
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height * (1 + 2 * row_number)
    aliens.add(alien)

# 修改update_screen()函数
def update_screen(ai_settings, screen, ship, bullets,
 aliens):
   # 绘制外星人,放在绘制子弹的代码后面,让外星人的图像覆盖掉子弹的图像
    aliens.draw(screen)

让外星舰队动起来

.补充settings.py模块
class Settings:
    def __init__(self):
     
        self.fleet_drop_speed = 10
        # 外星舰队方向标志:1向右,-1向左
        # 也可以用如left, right之类的标志,但这样会很麻烦
        self.fleet_direction = 1

击杀外星人

修改game_functions.py

def update_bullets(bullets, aliens, ship, screen, ai_settings):
  

    check_bullet_alien_collisions (ai_settings, screen, ship, aliens, bullets)

def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
    """检测是否有子弹击中了外星人,如果有,就删除相应的子弹和外星人"""
    # 下一篇中我们将用该变量实现分数统计
    collisions = pygame.sprite.groupcollide (bullets, aliens, True, True)

    # 如果外星人被消灭光,则生成新的外星人舰队
    if len (aliens) == 0:
        # 删除现有的子弹并创建新的舰队
        bullets.empty ()
        create_fleet (ai_settings, screen, ship, aliens)
注:sprite.groupcollide()方法用于检测对象之间的碰撞它将bullets中的每个子弹的rect与aliens中的每个外星人的rect进行比较,并返回一个字典。

2.修改alien_invasion.py

游戏结束

  1. 创建GameStats类,存放在game_stats.py文件中
class GameStats:
    """跟踪游戏的统计信息"""
    def __init__(self, ai_settings):
        """初始化统计信息"""
        # 用于控制游戏启动与否
        self.game_active = True
        self.ai_settings = ai_settings
        self.reset_stats()
    def reset_stats(self):
        """初始化在游戏运行期间可能变化的统计信息"""
        # 重置飞船数
        self.ships_left = self.ai_settings.ship_limit
  1. 修改settings.py
class Settings:
    def __init__(self):
       """初始化游戏的设置"""
        # 屏幕设置
      
        # 设置飞船数量限制
        self.ship_limit = 3
        

  1. 响应飞船与外星人的碰撞,修改game_functions.py
 # 增加了参数和碰撞检测
def update_aliens(ai_settings, aliens, ship, screen, bullets, stats):
    -- snip --
    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, ship, aliens, bullets)

    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets
  1. 修改主程序alien_invasion.py类
 # 开始游戏的主循环
while True:
    gf.check_events (ai_settings, screen, ship, bullets)
    # 决定程序运行时该执行的部分
    if stats.game_active:
        ship.update ()
        gf.update_bullets (bullets, aliens, ship, screen, ai_settings)
        gf.update_aliens (ai_settings, aliens, ship, screen, bullets, stats)

    gf.update_screen (ai_settings, screen, ship, bullets, aliens)

四、创建游戏开始按钮

添加Play按钮,创建Button类

  1. 这个类放在button.py模块中
import pygame
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 = (255, 255, 255)
        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)

游戏加速

修改setting类

class Settings:
    def __init__(self):
        -- snip --
        # 以什么样的速度提节奏
        self.speedup_scale = 1.1
        # 前面有四个属性放到了该方法中
        self.initialize_dynamic_settings()
    def initialize_dynamic_settings(self):
        """初始化随游戏进行而变化的设置"""
        self.ship_speed_factor = 1.5
        self.bullet_speed_factor = 3
        self.alien_speed_factor = 1
        # 外星舰队方向标志:1向右,-1向左
        self.fleet_direction = 1
    def increase_speed(self):
        """提高速度"""
        self.ship_speed_factor *= self.speedup_scale
        self.bullet_speed_factor *= self.speedup_scale
        self.alien_speed_factor *= self.speedup_scale

注:需要修改的四个参数放到了initialize_dynamic_settings()方法中,increase_speed()方法用于动态改变游戏参数

五、对游戏计分

新增scoreboard.py

import pygame
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()
        self.prep_level()
        self.prep_ships()
    def prep_score(self):
        """将得分转换为图片"""
        rounded_score = 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)
        # 将得分放在屏幕右上角
        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):
        """将最高得分转化为图像"""
        high_score = 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)
        # 将最高得分放在屏幕顶部中央
        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):
        """将等级转化为图像"""
          self.level_image = self.font.render(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.top = self.score_rect.bottom + 10
    def prep_ships(self):
        """显示还余下多少艘飞船"""
        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):
        """在屏幕上显示得分板"""
        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)

修改settings.py,设置外星人的分数,外星人分数增长的速度

class Settings:
    def __init__(self):
        -- snip --
        # 外星人点数的提高速度
        self.score_scale = 1.5
        self.initialize_dynamic_settings()
    def initialize_dynamic_settings(self):
        -- snip --
        # 记分, 每一个外星人的分数
        self.alien_points = 50
    def increase_speed(self):
        -- snip --
        # 动态增加每个外星人的分数
        self.alien_points = int(self.alien_points * self.score_scale)
  1. 修改game_stats.py
class GameStats:
    def __init__(self, ai_settings):
        -- snip --
        # 在任何情况下都不应重置最高得分
        self.high_score = 0
    def reset_stats(self):
        -- snip -- 

        self.score = 0
        self.level = 1

修改主程序alien_invasion.py

from scoreboard import Scoreboard

def run_game():
    # 创建计分板
    score = Scoreboard(ai_settings, screen, stats)
    # 开始游戏的主循环
    while True:
        # 添加score参数
        gf.check_events(ai_settings, screen, ship, bullets, stats, play_button,
                        aliens, score)
        if stats.game_active:
            ship.update()
            # 添加score参数
            gf.update_bullets(bullets, aliens, ship, screen, ai_settings, stats, score)
            # 添加score参数
            gf.update_aliens(ai_settings, aliens, ship, screen, bullets, stats, score)
        # 添加score参数
        gf.update_screen(ai_settings, screen, ship, bullets, aliens, stats,
                         play_button, score)

修改game_functions.py

 # 增加score参数
def check_events(ai_settings, screen, ship, bullets, stats, play_button, aliens, score):
    for event in pygame.event.get ():
        -- snip - -
        elif event.type == pygame.MOUSEBUTTONDOWN:
        mouse_x, mouse_y = pygame.mouse.get_pos ()
        # 增加score参数, 该函数有所改动
        check_play_button (stats, play_button, mouse_x, mouse_y, ai_settings,
                           screen, ship, aliens, bullets, score)
# 增加score参数
def update_bullets(bullets, aliens, ship, screen, ai_settings, stats, score):
    -- snip - -
    # 增加score参数,该函数有所改动
    check_bullet_alien_collisions (ai_settings, screen, ship, aliens, bullets, stats, score)
# 增加score参数
def update_aliens(ai_settings, aliens, ship, screen, bullets, stats, score):
    -- snip - -
    if pygame.sprite.spritecollideany (ship, aliens):
        # 增加score参数,该函数有所改动
        ship_hit (ai_settings, stats, screen, ship, aliens, bullets, score) 

    # 增加score参数,该函数有所改动
    check_aliens_bottom (ai_settings, stats, screen, ship, aliens, bullets, score)
# 增加score参数,该函数有所改动
def update_screen(ai_settings, screen, ship, bullets, aliens, stats, play_button, score):
    -- snip - -
    aliens.draw (screen)
    # 在if语句前面添加绘制计分板的代码
    # 显示得分
    score.show_score ()
    if not stats.game_active:
        play_button.draw_button ()

修改check_play_button()函数

# 添加了score参数
def check_play_button(stats, play_button, mouse_x, mouse_y, ai_settings, screen,
                      ship, aliens, bullets, score):
    """在玩家单机Play按钮时开始新游戏"""
    if play_button.rect.collidepoint (mouse_x,
                                      mouse_y) and not stats.game_active:
        stats.game_active = True  # 这一句不是新增的
        score.prep_score ()
        score.prep_high_score ()
        score.prep_level ()
        score.prep_ships ()

注:数列表添加了score参数,if判断中还添加了四行生成计分板的代码。之所以这里要添加这四行代码,其实是为了当你重新开始(也就是第二次及以后点击Play按钮)游戏时,计分板能正确显示

修改update_screen()函数

# 增加了score参数
def update_screen(ai_settings, screen, ship, bullets, aliens, stats, play_button, score):
    -- snip - -
    # 增加显示得分的代码
    score.show_score ()
    if not stats.game_active:

修改update_bullets()和update_aliens()函数

def update_bullets(bullets, aliens, ship, screen, ai_settings, stats, score):
    check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets, stats, score)
def update_aliens(ai_settings, aliens, ship, screen, bullets, stats, score):
 
    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens): 

        ship_hit(ai_settings, stats, screen, ship, aliens, bullets, score)
    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets, score)

修改check_bullet_alien_collisions()函数

def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets, stats, score):
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            # 其实这里可以将其放到for循环之外,应为并不能立刻就呈现分数变化
            # 要等到主程序中的update_screen()中才能呈现
            score.prep_score()
        # 该函数是新增的
        check_high_score(stats, score)
    if len(aliens) == 0:
        # 删除现有的子弹并创建新的舰队
        bullets.empty()
        ai_settings.increase_speed()
        # 提高等级
        stats.level += 1
        score.prep_level()
        create_fleet(ai_settings, screen, ship, aliens)
 注:collisions是一个字典,这里子弹是键,该子弹消灭的外星人对象为值(是个列表),还新增了一	个更新最高积分的函数check_high_score()
def check_high_score(stats, score):
    """检查是否诞生了新的最高得分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        score.prep_high_score()

修改ship_hit()和check_aliens_bottom()函数

def ship_hit(ai_settings, stats, screen, ship, aliens, bullets, score):
    if stats.ships_left > 0:
        stats.ships_left -= 1
        # 更新记分牌
        score.prep_ships()

运行主程序截图

在这里插入图片描述

六、分为九个模块分别展示完整代码

alien.py

import pygame
from pygame.sprite import Sprite

class Alien(Sprite):
    """表示单个外星人的类"""

    def __init__(self, ai_settings, screen):
        """初始化外星人并设置其他位置"""
        super(Alien, self).__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 blitme(self):
        """在指定位置绘制外星人"""
        self.screen.blit(self.image, self.rect)

    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_factor * self.ai_settings.fleet_direction)
        self.rect.x = self.x

alien_invasion.py

import pygame

from settings import Settings
from game_stats import GameStats
from button import Button
from ship import Ship
from pygame.sprite import Group
import game_functions as gf
from scoreboard import Scoreboard


def run_game():
    pygame.init()  # 初始化背景设置
    ai_settings = Settings()  # 全局设置

    screen = pygame.display.set_mode(  # 创建screen显示窗口
        (ai_settings.screen_width, ai_settings.screen_height)
    )
    pygame.display.set_caption('Alien Invasion')  # 标题
    # 新建Play按钮
    play_button = Button(ai_settings, screen, "Play")
    # 创建一个用于存储游戏统计信息的实例,并创建记分牌
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 创建飞船
    ship = Ship(ai_settings, screen)
    # 创建子弹编组
    bullets = Group()

    # 创建一个外星人
    aliens = Group()
    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 开始游戏主循环
    while True:
        # 监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)

        if stats.game_active:
            # 移动飞船
            gf.update_ship(ship)
            # 更新子弹位置
            gf.update_bullets(ai_settings, screen, stats, 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)


run_game()

bullet.py

import pygame
from pygame.sprite import Sprite
import time

class Bullet(Sprite):
    '''飞船子弹进行管理'''

    def __init__(self,ai_settings,screen,ship):
        super(Bullet,self).__init__()
        self.screen = screen

        # 创建子弹矩形初始位置(0,0,3,15)分别对应lef,top,宽,高
        self.rect = pygame.Rect(0,0,
        ai_settings.bullet_width, ai_settings.bullet_height)

        self.rect.centerx = ship.rect.centerx  # 设置中心点x轴坐标跟飞船一致
        self.rect.top = ship.rect.top          # 设置y轴坐标顶部跟飞船一致

        # 设置成小数进行计算
        self.top = float(self.rect.top)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        self.top -=self.speed_factor
        self.rect.top = self.top
        print(self.rect.top)

    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 = (255, 255, 255)
        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_functions.py

import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep


def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):
    # 监视键盘和鼠标事件
    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):
    """在玩家单击Play按钮时开始游戏"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        # 重置游戏设置
        ai_settings.initialize_dynamic_settings()

        # 隐藏光标
        pygame.mouse.set_visible(False)
        # 重置游戏统计信息
        stats.reset_stats()
        stats.game_active = True

        # 重置计分牌图像
        sb.prep_score()
        sb.prep_high_score()
        sb.prep_level()
        sb.prep_ships()

        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()

        # 创建一群新的外星人,并让飞船居中
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()


def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):
    '''更新屏幕上的图片,并切换到新屏幕'''
    screen.fill(ai_settings.bg_color)  # 设置背景颜色
    ship.blitme()  # 绘制飞船
    aliens.draw(screen)
    # 循环子弹组里面的元素,进行绘制 为空时不执行
    for bullet in bullets.sprites():
        bullet.draw_bullet()  # 绘制子弹
    # 显示得分
    sb.show_score()
    # 如果游戏处于非活跃状态,就显示Play按钮
    if not stats.game_active:
        play_button.draw_button()
    # 显示最新屏幕,擦拭旧屏幕
    pygame.display.flip()
    # print('1')


def check_keydown_events(event, ai_settings, screen, ship, bullets):
    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):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
    '''更新子弹位置,删除子弹'''
    bullets.update()  # 子弹组每个成员执行self.update()操作
    for bullet in bullets.sprites():
        if bullet.rect.bottom <= 0:  # 子弹出界 删除
            bullets.remove(bullet)
    check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets)


def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):
    """响应外星人和子弹的碰撞"""
    # 删除发生碰撞的子弹和外星人
    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:
        # 删除现有的子弹并新建一群外星人,加快游戏进度节奏
        bullets.empty()
        ai_settings.increase_speed()

        # 提高等级
        stats.level += 1
        sb.prep_level()

        create_fleet(ai_settings, screen, ship, aliens)


def update_ship(ship):
    ship.update()


def fire_bullet(ai_settings, screen, ship, bullets):
    # 创建一个子弹对象 加入到子弹组
    if len(bullets) < ai_settings.bullets_allowed:  # 子弹少于允许值时再生成
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


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_number_rows(ai_settings, ship_height, alien_height):
    """计算屏幕可容纳多少行外星人"""
    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_aliens(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 + 2 * alien.rect.height * row_number
    aliens.add(alien)


def create_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_number_rows(ai_settings, ship.rect.height, alien.rect.height)

    # 创建第一行外星人
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            # 创建一个外星人并将其加入当前行
            create_aliens(ai_settings, screen, aliens, alien_number, 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 ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets):
    """响应被外星人撞到的飞船"""
    if stats.ships_left > 0:
        # 将ship_left减1
        stats.ships_left -= 1

        # 更新记分牌
        sb.prep_ships()

        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()
        # 创建一群新的外星人,并将飞船放到屏幕低端中央
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()
        # 暂停
        sleep(0.5)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


def check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets):
    """检查是否有外星人到达屏幕低端"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            # 像飞船被撞到一样进行处理
            ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)
            break


def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets):
    """更新外星人群中所有外星人的位置"""
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)
    # 检查是否有外星人到达屏幕低端
    check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)


def check_high_score(stats, sb):
    """检查是否诞生了新的最高纪录"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()

game_stats.py

class GameStats():
    """跟踪游戏的统计信息"""

    def __init__(self, ai_settings):
        """初始化统计信息"""
        self.ai_settings = ai_settings
        self.reset_stats()
        # 游戏刚启动时处于非活动状态
        self.game_active = False
        # 在任何情况下不应该重置最高分
        self.high_score = 0
        self.level = 1

    def reset_stats(self):
        """初始化在游戏运行期间可能变化的统计信息"""
        self.ships_left = self.ai_settings.ship_limit
        self.score = 0

scoreboard.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()
        self.prep_level()
        self.prep_ships()

    def prep_score(self):
        """将得分转换为一幅渲染的图像"""
        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)

        # 将得分放在右上角
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = 5

    def prep_high_score(self):
        """将最高得分转换为渲染图像"""
        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)

        # 将最高分放在屏幕最中央
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.centerx = self.screen_rect.centerx
        self.high_score_rect.top = 5

    def prep_level(self):
        """将等级转换为渲染图像"""
        self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color)

        # 将得分放在右上角
        self.level_rect = self.score_image.get_rect()
        self.level_rect.right = self.screen_rect.right
        self.level_rect.top = self.score_rect.bottom

    def prep_ships(self):
        """显示还剩下多少艘飞船"""
        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):
        """在屏幕上显示得分和等级"""
        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)

settings.py

class Settings():
    '''存储外星人入侵中所有的设置'''

    def __init__(self):
        '''初始化设置'''
        # 屏幕设置
        self.screen_width = 1200
        self.screen_height = 600
        self.bg_color = (230, 230, 230)  # 设置背景色  灰色

        # 飞船设置
        self.ship_limit = 3
        self.ship_image_path = 'images/ship.bmp'  # 飞船图片路径

        # 子弹设置
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60, 60, 60
        self.bullets_allowed = 3  # 允许屏幕中出现子弹的数量

        # 外星人设置
        self.fleet_drop_speed = 10

        # 以什么样的速度加快游戏节奏
        self.speedup_scale = 1.1
        # 外星人点数提高速度
        self.score_scale = 1.5

        self.initialize_dynamic_settings()

    def initialize_dynamic_settings(self):
        """初始化随游戏进行而变化的设置"""
        self.ship_speed_factor = 1.5
        self.bullet_speed_factor = 3
        self.alien_speed_factor = 1

        # fleet_direction为1表示向右移,为-1表示向左移
        self.fleet_direction = 1

        # 计分
        self.alien_points = 50

    def increase_speed(self):
        """提高速度设置,外星人点数"""
        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)
        print(self.alien_points)

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.ai_settings = ai_settings

        # 加载飞船图片、获取外接矩形
        self.image = pygame.image.load(self.ai_settings.ship_image_path)   # 加载图片
        self.image = pygame.transform.smoothscale(self.image,(40,60))
        self.rect = self.image.get_rect()   # 获取图片外接矩形
        self.screen_rect = screen.get_rect()        #获取屏幕外接矩形

        # 将每搜新飞船放到并木底部中心
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
        # 设置成浮点类型
        self.center = float(self.rect.centerx)      # self.rect.centerx设置不了浮点数 只能另设置一个变量进行运算

        # 移动标志
        self.moving_right = False
        self.moving_left = False

    def blitme(self):
        '''在指定位置绘制飞船'''
        self.screen.blit(self.image,self.rect)

    def update(self):
        # 向右移动飞船
        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 > self.screen_rect.left:
            self.center -= self.ai_settings.ship_speed_factor

        self.rect.centerx = self.center

    def center_ship(self):
        """让飞船在屏幕上居中"""
        self.center = self.screen_rect.centerx

本文地址:https://blog.csdn.net/qq_45621392/article/details/109800448

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

  • supervisor下的Dockerfile的多服务镜像封装操作

    supervisor下的Dockerfile的多服务镜像封装操作

    编写dockerfile文件配置yum源cd /tmp/dockervim dockerfilefrom rhel7expose 80 22 # 向外暴露80... [阅读全文]
  • python中绕过反爬虫的方法总结

    我们在登山的途中,有不同的路线可以到达终点。因为选择的路线不同,上山的难度也有区别。就像最近几天教大家获取数据的时候,断断续续的讲过header、地址ip等一些... [阅读全文]
  • python 如何停止一个死循环的线程

    python 如何停止一个死循环的线程

    进程想要执行任务就需要依赖线程。换句话说,就是进程中的最小执行单位就是线程,并且一个进程中至少有一个线程。那什么是多线程?提到多线程这里要说两个概念,就是串行和... [阅读全文]
  • 利用python+ffmpeg合并B站视频及格式转换的实例代码

    利用python+ffmpeg合并b站视频及格式转换 b站客户端下载的视频一般有两种格式:早期的多为blv格式(由flv格式转换而来,音视频轨道在同一文件下)。... [阅读全文]
  • python3爬虫中多线程的优势总结

    有些小伙伴跟小编讨论了python中使用多线程原理的问题,就聊到了关于python多线程的弊端问题,这点可能在使用的过程中大家会能感觉到。而且之前讲过的gil也... [阅读全文]
  • python3爬虫中引用Queue的实例讲解

    我们去一个受欢迎的地方买东西,难免会需要排队等待。如果有多个窗口的话,就会有不同队列的产生,当然每个队伍的人数也会出现参差不齐的现象。我们今天所要说的queue... [阅读全文]
  • Django URL参数Template反向解析

    一、 url参数在view中传递1、带参数名:通过named group方式传递指定参数,语法为: (?p<name>pattern), n... [阅读全文]
  • python3爬虫GIL修改多线程实例讲解

    python3爬虫GIL修改多线程实例讲解

    我们打开程序后,会发现电脑的内存和cpu发生了变化。在对于前者上面,自然是希望内容占用小,cpu的利用越高越好。那有没有什么方法可以让我们的cpu达到满状态的运... [阅读全文]
  • PyCharm Community安装与配置的详细教程

    PyCharm Community安装与配置的详细教程

    【内容】: 最近python挺火,空闲时间看了几个python视频,觉得简单易懂,开发效率高,应用范围广,值得学习。如下便开始搭建学习环境,即安装一款好用的... [阅读全文]
  • python爬虫快速响应服务器的做法

    不论是打开网页或者爬取一些资料的时候,我们想要的是计算机能在最短的时间内运行出结果,不然等待的时间过长会影响下一步工作的计划。这时候我们可以给计算机一个指令,限... [阅读全文]
验证码:
Copyright © 2017-2020  萬仟网 保留所有权利. 粤ICP备17035492号-1