Python实战——外星人入侵游戏

  • 项目简介
    • 1.准备工作
    • 2.代码部分
      • alien_invasion.py
      • alien.py
      • bullet.py
      • button.py
      • ship.py
      • settings.py
      • scoreboard.py
      • game_stats.py
      • game_functions.py
    • 3. 添加内容介绍
      • 添加的随着等级改变子弹设置
      • 保存最高分的文件,使得下次打开不重置最高分
      • 添加击中音效
    • 4. 遇到的bug
      • 类继承
      • 坐标更新
    • 5. 心得体会
    • 6. 下载资源

项目简介

经历三天时间完成为python实战小游戏,外星人入侵,主要完成了书目当中的主要功能。同时添加了一些自己定义的功能:每次保留历史最高分,随着等级的不断提升改变飞船子弹的相关设置,加入音效模块在集中外星人的时候击中音效。同时,简单写了几个遇到的bug,希望可以对大家有帮助,下载资源链接附在最后。

1.准备工作

对于小游戏的编写主要进行图片的配置

由于后续需要音频,加载特效音频

下载对应的pygame模块以及配置好python,具体的编写工具可以利用pycharm实现,相关安装配置工作可以在网站上搜索,很详细不再赘述

展现一下最终结果图

2.代码部分

alien_invasion.py

整个游戏的主流程界面,创建相关类和参数,以及推动游戏进行

import pygamefrom settings import Settingsfrom ship import Shipimport game_functions as gffrom pygame.sprite import Groupfrom game_stats import GameStatsfrom button import Buttonfrom scoreboard import Scoreboarddef run_game():# 初始化屏幕pygame.init()ai_settings = Settings()screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))pygame.display.set_caption("Alien Invasion")# 创建一个用于存储游戏统计信息的实例,并创建积分牌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)# 创建开始按钮play_button = Button(ai_settings, screen, "Play")# 开始游戏while True:gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)if stats.game_active:ship.update()# 飞船更新gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)# 子弹更新gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)# 每次循环都重新绘制屏幕gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)run_game()

alien.py

外星人类,主要进行外星人相关参数初始化以及在游戏进程当中的参数改变

import pygamefrom pygame.sprite import Spriteclass Alien(Sprite):""""表示单个外星人的类"""def __init__(self, ai_settings, screen):""""初始化单个外星人的位置"""super(Alien, self).__init__()self.screen = screenself.ai_settings = ai_settings# 加载外星人图像,并且设置其rect属性self.image = pygame.image.load('images/alien.bmp')self.rect = self.image.get_rect()# 每个外星人最初在屏幕左上角附近self.rect.x = self.rect.widthself.rect.y = self.rect.height# 存储外星人的准确位置self.x = float(self.rect.x)def blitme(self):""""在指定位置绘制外星人"""self.screen.blit(self.image, self.rect)def update(self):"""向右移动外星人"""self.x += self.ai_settings.alien_speed_factor * self.ai_settings.fleet_directionself.rect.x = self.xdef check_edges(self):"""如果外星人位于屏幕边缘,就返回True"""screen_rect = self.screen.get_rect()if self.rect.right >= screen_rect.right:return Trueelif self.rect.left <= 0:return True

bullet.py

子弹类,主要进行子弹的初始化和显示子弹图形的操作

import pygamefrom pygame.sprite import Spriteclass 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.centerxself.rect.top = ship.rect.top# 存储用小数表示的子弹位置self.y = float(self.rect.y)self.color = ai_settings.bullet_colorself.speed_factor = ai_settings.bullet_speed_factordef update(self):self.y -= self.speed_factorself.rect.y = self.ydef draw_bullet(self):pygame.draw.rect(self.screen,self.color,self.rect)

button.py

按钮模块,主要是绘制和显示了开始玩游戏的按钮,可以根据自己的需要设置其他的按钮,思路相同

import pygame.fontclass Button():def __init__(self, ai_settings, screen, msg):self.screen = screenself.screen_rect = screen.get_rect()# 设置按钮的尺寸和其他属性self.width, self.height = 200, 50self.button_color = (0, 255, 0)self.text_coclor = (255, 255, 255)self.font = pygame.font.SysFont(None, 48)# 使得pygame的文本渲染到屏幕上,默认字体,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_coclor,self.button_color)# 将存储在msg当中的文本渲染为图像,启用反锯齿可以使得文本边缘更平滑self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.centerdef draw_button(self):self.screen.fill(self.button_color, self.rect)# 绘制矩形self.screen.blit(self.msg_image, self.msg_image_rect) # 传递一副图像以及与该图像相关联的rect图像

ship.py

初始化和更新飞船的信息,以及上下左右移动的内容。注释掉的部分是上下移动,也可以添加进去

import pygamefrom pygame.sprite import Spriteclass Ship(Sprite):def __init__(self, ai_settings, screen):"""初始化飞船,并且设置其初始位置"""super(Ship,self).__init__()self.screen = screenself.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.centerxself.rect.bottom = self.screen_rect.bottomself.centerx = float(self.rect.centerx)# self.centery = float(self.rect.centery)# 可持续移动self.moving_right = Falseself.moving_left = False# self.moving_up = False# self.moving_down = Falsedef update(self):if self.moving_right and self.rect.right < self.screen_rect.right:self.centerx += self.ai_settings.ship_speed_factorif self.moving_left and self.rect.left > 0:self.centerx -= self.ai_settings.ship_speed_factor# if self.moving_up and self.rect.top > 0:# # self.rect.centerx -= self.ai_settings.ship_speed_factor# self.centery -= self.ai_settings.ship_speed_factor# if self.moving_down and self.rect.bottom < self.screen_rect.bottom:# # self.rect.centerx -= self.ai_settings.ship_speed_factor# self.centery += self.ai_settings.ship_speed_factorself.rect.centerx = self.centerx# self.rect.centery = self.centerydef blitme(self):self.screen.blit(self.image, self.rect)def center_ship(self):self.center=self.screen_rect.centerx

settings.py

所有部分的初始化设置部分,和游戏当中更改设置部分,可以让整个游戏的参数更清晰明了

class Settings:def __init__(self):# 初始化屏幕设置self.screen_width = 960self.screen_height = 720self.bg_color = (150, 205, 205)# 飞船设置self.ship_limit = 3# 子弹设置self.bullet_width = 5self.bullet_height = 15self.bullet_color = 0, 0, 0self.bullets_allowed = 3# 外星人设置self.fleet_drop_speed = 10# 以什么样的速度加快游戏节奏self.speedup_scale = 1.1# 外星人点数的提高速度self.score_scale = 1.5self.initialize_dynamic_settings()# 记分self.alien_points = 50def initialize_dynamic_settings(self):"""初始化随游戏变化而变化的设置"""self.ship_speed_factor = 1.5self.bullet_speed_factor = 3self.alien_speed_factor = 1# 1为向右移,-1为向左移self.fleet_direction = 1def increase_speed(self):"""提高速度设置"""self.ship_speed_factor *= self.speedup_scaleself.bullet_speed_factor *= self.speedup_scaleself.alien_speed_factor *= self.speedup_scaleself.alien_points = int(self.alien_points * self.score_scale)print(self.alien_points)

scoreboard.py

更新和显示得分和等级信息

import pygame.fontfrom pygame.sprite import Groupfrom ship import Shipclass Scoreboard():"""显示得分信息的类"""def __init__(self, ai_settings, screen, stats):"""初始化显示得分涉及的属性"""self.screen = screenself.screen_rect = screen.get_rect()self.ai_settings = ai_settingsself.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))# 将stats.score的值圆整为最近的10的整数倍,并将结果存储到该数值当中score_str = 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 - 20self.score_rect.top = 20def prep_high_score(self):"""将最高得分转换为渲染图像"""high_score = int(round(self.stats.high_score, -1))# 将stats.score的值圆整为最近的10的整数倍,并将结果存储到该数值当中high_score_str = 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.right = self.score_rect.rightself.high_score_rect.top = self.score_rect.bottomdef prep_level(self):"""将等级渲染成为图像"""level_str = str("Level: ") + str(self.stats.level)self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color)# 将等级显示在右下角self.level_rect = self.level_image.get_rect()self.level_rect.right = self.score_rect.rightself.level_rect.bottom = self.screen_rect.bottom - 20def 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.widthship.rect.y = 10self.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)

game_stats.py

整个游戏的统计信息模块,主要统计得分、等级,以及确定游戏是否进行

class GameStats():def __init__(self, ai_settings):self.ai_settings = ai_settingsself.reset_stats()self.game_active = False# 在任何情况下都不重置最高分# self.high_score=0def reset_stats(self):self.ships_left = self.ai_settings.ship_limitself.score=0self.level=1self.high_score = 0# 比较文件中的最高分和现在的最高分save_high_score=self.read_high_score()if int(save_high_score)>self.high_score:self.high_score=int(save_high_score)def read_high_score(self):Note = open('x.txt', mode='r')content = Note.read()print(content)Note.close()return content

game_functions.py

整个项目最核心的部分,放置着控制游戏进行的各种功能模块

import sysimport pygamefrom bullet import Bulletfrom alien import Alienfrom time import sleepdef check_keydown_events(event, ai_settings, screen, ship, bullets):"""检查键盘按下的事件响应"""if event.key == pygame.K_RIGHT:ship.moving_right = Trueelif event.key == pygame.K_LEFT:ship.moving_left = Trueelif event.key == pygame.K_SPACE:fire_bullets(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 = Falseelif event.key == pygame.K_LEFT:ship.moving_left = Falsedef write_high_score(stats):Note = open('x.txt', mode='w')Note.write(str(stats.high_score) + '\n')Note.close()def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):"""响应鼠标和键盘"""for event in pygame.event.get():if event.type == pygame.QUIT:write_high_score(stats)sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event, ai_settings, screen, ship, bullets)# print(event.key)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:# 该函数检查鼠标按下部分的x,y坐标是否在play的矩形框内# 重置游戏设置ai_settings.initialize_dynamic_settings()# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏统计信息stats.reset_stats()stats.game_active = True# 重置积分牌sb.prep_level()sb.prep_score()sb.prep_high_score()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)# 子弹循环绘制for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)# 对编组调用draw,将会自动绘制每个元素# 显示得分sb.show_score()# 如果游戏处于非活动状态,就显示play按钮if not stats.game_active:play_button.draw_button()# 绘制play按钮# 让最新绘制可见pygame.display.flip()def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):"""更新一些个子弹设置"""# 更新子弹的位置bullets.update()# 删除已经消失的子弹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):"""检查是否诞生了新的最高分"""if stats.score > stats.high_score:stats.high_score = stats.scoresb.prep_high_score()def check_level_provide_bullets(ai_settings, stats, sb):"""检查等级是否达到最够高,可以提供大额子弹"""dream_level_1 = 2dream_level_2 = 3dream_level_3 = 4if stats.level >= dream_level_1:ai_settings.bullet_width = 15elif stats.level >= dream_level_2:ai_settings.bullets_allowed = 5ai_settings.bullet_width = 20elif stats.level >= dream_level_3:ai_settings.bullet_speed_factor = 1.5 * ai_settings.bullet_speed_factorsb.prep_level()def play_sound():pygame.mixer.init()pygame.mixer.music.load('z_biubiu.mp3')pygame.mixer.music.play()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():# 确保每个外星人都计入,防止一个子弹打中多个外星人等情况出现积分错误play_sound()stats.score += ai_settings.alien_pointssb.prep_score()check_high_score(stats, sb)if len(aliens) == 0:# 删除现有子弹并且加快游戏进度bullets.empty()ai_settings.increase_speed()# 消灭所有外星人,提升一个等级stats.level += 1# sb.prep_level()check_level_provide_bullets(ai_settings, stats, sb)create_fleet(ai_settings, screen, ship, aliens)# 删除现有的子弹并且创建新的一群外星人def fire_bullets(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_x(ai_settings, alien_width):"""计算每行可以容纳多少外星人"""available_space_x = ai_settings.screen_width - 2 * alien_widthnumber_aliens_x = int(available_space_x / (2 * alien_width))return number_aliens_xdef 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_rowsdef create_alien(ai_settings, screen, aliens, alien_number, row_number):"""创建一个外星人并将其放在当前行"""alien = Alien(ai_settings, screen)# 创建第一个外星人并且将其加入其中alien_width = alien.rect.widthalien.x = alien_width + 2 * alien_width * alien_numberalien.rect.x = alien.x# alien.rect.x=alien.rect.width+2*alien.rect.width*alien_number # 注意不可以使用这行,因为不更新alien.x 会导致产生的外星人都在一列重复着alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_numberaliens.add(alien)def create_fleet(ai_settings, screen, ship, aliens):"""创建外星人群"""alien = Alien(ai_settings, screen)number_aliens_x = get_number_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)# print(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)breakdef change_fleet_direction(ai_settings, aliens):"""将整群外星人下移,并且改变他们的方向"""for alien in aliens.sprites():alien.rect.y += ai_settings.fleet_drop_speedai_settings.fleet_direction *= -1def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets):"""响应被外星人碰到的飞船"""if stats.ships_left > 0: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 = Falsepygame.mouse.set_visible(True)def check_aliens_bottom(ai_settings, screen, stats, 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, screen, stats, sb, ship, aliens, bullets)breakdef 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, screen, stats, sb, ship, aliens, bullets)check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets)

3. 添加内容介绍

添加的随着等级改变子弹设置

根据不同的等级设置子弹参数,在game_functions.py当中添加函数

def check_level_provide_bullets(ai_settings, stats, sb):"""检查等级是否达到最够高,可以提供大额子弹"""dream_level_1 = 2dream_level_2 = 3dream_level_3 = 4if stats.level >= dream_level_1:ai_settings.bullet_width = 15elif stats.level >= dream_level_2:ai_settings.bullets_allowed = 5ai_settings.bullet_width = 20elif stats.level >= dream_level_3:ai_settings.bullet_speed_factor = 1.5 * ai_settings.bullet_speed_factorsb.prep_level()

之后在game_functions.py的check_bullet_alien_collisions函数当中进行调用,在消灭所有外星人更新等级之后,进行等级查看修改子弹参数

if len(aliens) == 0:# 删除现有子弹并且加快游戏进度bullets.empty()ai_settings.increase_speed()# 消灭所有外星人,提升一个等级stats.level += 1# sb.prep_level()check_level_provide_bullets(ai_settings, stats, sb)create_fleet(ai_settings, screen, ship, aliens)# 删除现有的子弹并且创建新的一群外星人

保存最高分的文件,使得下次打开不重置最高分

在sys.exit( )之前写入当前最高分

def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):"""响应鼠标和键盘"""for event in pygame.event.get():if event.type == pygame.QUIT:write_high_score(stats)sys.exit()
def write_high_score(stats):Note = open('x.txt', mode='w')Note.write(str(stats.high_score) + '\n')Note.close()

在game_stats.py当中读取文件显示最高分,进行调用

def read_high_score(self):Note = open('x.txt', mode='r')content = Note.read()print(content)Note.close()return content
 def reset_stats(self):self.ships_left = self.ai_settings.ship_limitself.score=0self.level=1self.high_score = 0# 比较文件中的最高分和现在的最高分save_high_score=self.read_high_score()if int(save_high_score)>self.high_score:self.high_score=int(save_high_score)

添加击中音效

在game_functions.py编写添加音效的函数

def play_sound():pygame.mixer.init()pygame.mixer.music.load('z_biubiu.mp3')pygame.mixer.music.play()

每次击中,在函数check_bullet_alien_collisions中进行调用

if collisions:for aliens in collisions.values():# 确保每个外星人都计入,防止一个子弹打中多个外星人等情况出现积分错误play_sound()stats.score += ai_settings.alien_pointssb.prep_score()check_high_score(stats, sb)

4. 遇到的bug

类继承

主要遇到的问题是在进行显示剩余飞船时出现的

attributeerror: 'ship' object has no attribute 'add_internal'

其主要原因是没有在ship类里面继承Sprite,添加之后解决

class Ship(Sprite):

出现错误提示的代码

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.widthship.rect.y = 10self.ships.add(ship)

在使用类进行列表的操作,即添加等相关内容时,注意类继承问题,alien,bullet没有进行类似编写可能同样出现问题

坐标更新

最近下外星人坐标更新时,发现这部分代码有点繁琐,尝试简化发现把所有外星人全部放在了同一列,图像仅仅显示一列外星人。这主要是因为在alien.update( )里面是根据x坐标进行创建,而不是rect.x进行创建

alien_width = alien.rect.widthalien.x = alien_width + 2 * alien_width * alien_numberalien.rect.x = alien.x# alien.rect.x=alien.rect.width+2*alien.rect.width*alien_number # 注意不可以使用这行,因为不更新alien.x 会导致产生的外星人都在一列重复着

5. 心得体会

主要是进行了分模块操作解决功能,这种分级简化问题的思维方式很重要,在日后的学习中拆解问题是解决问题的重要步骤。而且这种有条理性的规划任务对自己的帮助很大。

6. 下载资源

图片下载
https://www.nostarch.com/pythoncrashcourse
音效下载
https://www.aigei.com/