经历三天时间完成为python实战小游戏,外星人入侵,主要完成了书目当中的主要功能。同时添加了一些自己定义的功能:每次保留历史最高分,随着等级的不断提升改变飞船子弹的相关设置,加入音效模块在集中外星人的时候击中音效。同时,简单写了几个遇到的bug,希望可以对大家有帮助,下载资源链接附在最后。
对于小游戏的编写主要进行图片的配置
由于后续需要音频,加载特效音频
下载对应的pygame模块以及配置好python,具体的编写工具可以利用pycharm实现,相关安装配置工作可以在网站上搜索,很详细不再赘述
整个游戏的主流程界面,创建相关类和参数,以及推动游戏进行
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
def run_game():
# 初始化屏幕
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("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()
外星人类,主要进行外星人相关参数初始化以及在游戏进程当中的参数改变
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 update(self):
"""向右移动外星人"""
self.x += self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction
self.rect.x = self.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
子弹类,主要进行子弹的初始化和显示子弹图形的操作
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
# 存储用小数表示的子弹位置
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
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen,self.color,self.rect)
按钮模块,主要是绘制和显示了开始玩游戏的按钮,可以根据自己的需要设置其他的按钮,思路相同
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_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.center
def draw_button(self):
self.screen.fill(self.button_color, self.rect) # 绘制矩形
self.screen.blit(self.msg_image, self.msg_image_rect) # 传递一副图像以及与该图像相关联的rect图像
初始化和更新飞船的信息,以及上下左右移动的内容。注释掉的部分是上下移动,也可以添加进去
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('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
self.centerx = float(self.rect.centerx)
# self.centery = float(self.rect.centery)
# 可持续移动
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.centerx += self.ai_settings.ship_speed_factor
if 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_factor
self.rect.centerx = self.centerx
# self.rect.centery = self.centery
def blitme(self):
self.screen.blit(self.image, self.rect)
def center_ship(self):
self.center=self.screen_rect.centerx
所有部分的初始化设置部分,和游戏当中更改设置部分,可以让整个游戏的参数更清晰明了
class Settings:
def __init__(self):
# 初始化屏幕设置
self.screen_width = 960
self.screen_height = 720
self.bg_color = (150, 205, 205)
# 飞船设置
self.ship_limit = 3
# 子弹设置
self.bullet_width = 5
self.bullet_height = 15
self.bullet_color = 0, 0, 0
self.bullets_allowed = 3
# 外星人设置
self.fleet_drop_speed = 10
# 以什么样的速度加快游戏节奏
self.speedup_scale = 1.1
# 外星人点数的提高速度
self.score_scale = 1.5
self.initialize_dynamic_settings()
# 记分
self.alien_points = 50
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
self.alien_points = int(self.alien_points * self.score_scale)
print(self.alien_points)
更新和显示得分和等级信息
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)) # 将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 - 20
self.score_rect.top = 20
def 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.right
self.high_score_rect.top = self.score_rect.bottom
def 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.right
self.level_rect.bottom = self.screen_rect.bottom - 20
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)
整个游戏的统计信息模块,主要统计得分、等级,以及确定游戏是否进行
class GameStats():
def __init__(self, ai_settings):
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
# 在任何情况下都不重置最高分
# self.high_score=0
def reset_stats(self):
self.ships_left = self.ai_settings.ship_limit
self.score=0
self.level=1
self.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
整个项目最核心的部分,放置着控制游戏进行的各种功能模块
import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep
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_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 = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def 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.score
sb.prep_high_score()
def check_level_provide_bullets(ai_settings, stats, sb):
"""检查等级是否达到最够高,可以提供大额子弹"""
dream_level_1 = 2
dream_level_2 = 3
dream_level_3 = 4
if stats.level >= dream_level_1:
ai_settings.bullet_width = 15
elif stats.level >= dream_level_2:
ai_settings.bullets_allowed = 5
ai_settings.bullet_width = 20
elif stats.level >= dream_level_3:
ai_settings.bullet_speed_factor = 1.5 * ai_settings.bullet_speed_factor
sb.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_points
sb.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_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_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.x=alien.rect.width+2*alien.rect.width*alien_number # 注意不可以使用这行,因为不更新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_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)
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, 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 = False
pygame.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)
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, screen, stats, sb, ship, aliens, bullets)
check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets)
根据不同的等级设置子弹参数,在game_functions.py当中添加函数
def check_level_provide_bullets(ai_settings, stats, sb):
"""检查等级是否达到最够高,可以提供大额子弹"""
dream_level_1 = 2
dream_level_2 = 3
dream_level_3 = 4
if stats.level >= dream_level_1:
ai_settings.bullet_width = 15
elif stats.level >= dream_level_2:
ai_settings.bullets_allowed = 5
ai_settings.bullet_width = 20
elif stats.level >= dream_level_3:
ai_settings.bullet_speed_factor = 1.5 * ai_settings.bullet_speed_factor
sb.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_limit
self.score=0
self.level=1
self.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_points
sb.prep_score()
check_high_score(stats, sb)
主要遇到的问题是在进行显示剩余飞船时出现的
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.width
ship.rect.y = 10
self.ships.add(ship)
在使用类进行列表的操作,即添加等相关内容时,注意类继承问题,alien,bullet没有进行类似编写可能同样出现问题
最近下外星人坐标更新时,发现这部分代码有点繁琐,尝试简化发现把所有外星人全部放在了同一列,图像仅仅显示一列外星人。这主要是因为在alien.update( )里面是根据x坐标进行创建,而不是rect.x进行创建
alien_width = alien.rect.width
alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
# alien.rect.x=alien.rect.width+2*alien.rect.width*alien_number # 注意不可以使用这行,因为不更新alien.x 会导致产生的外星人都在一列重复着
主要是进行了分模块操作解决功能,这种分级简化问题的思维方式很重要,在日后的学习中拆解问题是解决问题的重要步骤。而且这种有条理性的规划任务对自己的帮助很大。
图片下载
https://www.nostarch.com/pythoncrashcourse
音效下载
https://www.aigei.com/