@Python编程从入门到实践 Python项目练习
九、添加Play按钮
一、创建Button类
先让游戏一开始为非活动状态
# game_stats.py
# --snip--
self.game_active = False
# def reset_stats(self):
# --snip--
button类为带标签的实心矩形,将“play”字符串渲染为图像,放在矩形上方居中
# 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, 0, 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
# 按钮的标签只需创建一次,即将字符串msg渲染为图像
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)
二、绘制按钮
在alien_invasion.py中创建实例,修改up_screen(),让游戏处于非活动状态显示按钮
# alien_invasion.py
# --snip--
# 创建play按钮
play_button = Button(ai_settings, screen, "Play")
# 开始游戏主循环
while True:
# --snip--
# 每次循环重绘窗口并更新屏幕
gf.update_screen(ai_settings, screen, stats, ship, passenger_group, bullet_group,play_button)
# game_functions.py
# --snip--
# 如果游戏处于非活动状态,就绘制Play按钮
if not stats.game_active:
play_button.draw_button()
# --snip--
三、点击按钮
玩家点击按钮时,应重置游戏统计信息,保证下次游戏不重复。而且,只有在游戏激活状态为False时,点击才有效。
# game_functions.py
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# sys.exit()
# --snip--
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
check_play_button(ai_settings, screen, stats, play_button, ship,
passenger_group, bullet_group, mouse_x, mouse_y)
def check_play_button(ai_settings, screen, stats, play_button, ship,
passenger_group, bullet_group, mouse_x, mouse_y):
"""在玩家单击Play按钮时开始游戏"""
button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
if button_clicked and not stats.game_active: # 检查鼠标点击位置是否在play范围内
# 隐藏光标
pygame.mouse.set_visible(False)
# 重置游戏统计信息
stats.reset_stats()
stats.game_active = True
# 清空外星人列表和子弹列表
passenger_group.empty()
bullet_group.empty()
# 创建一群新的外星人,并在飞船居中
create_fleet(ai_settings, screen, ship, passenger_group)
ship.center_ship()
注意,修改alien_invasion.py中,check_events的形参,与game_functions.py中的同步。