更新 'alien_invasion.py'

This commit is contained in:
206530228 2021-06-24 08:37:56 +08:00
parent 7a76545e06
commit 8d4cf98c50
1 changed files with 31 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import pygame
from settings import Settings
from game_stats import GameStats
from button import Button
from ship import Ship
from bullet import Bullet
from alien import Alien
@ -31,6 +32,9 @@ class AlienInvasion:
self._create_fleet()
# 创建Play按钮
self.play_button = Button(self,"Play")
# 设置背景色
self.bg_color = (230, 230, 230)
@ -123,6 +127,28 @@ class AlienInvasion:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
self._check_play_button(mouse_pos)
def _check_play_button(self,mouse_pos):
"""在玩家单机Play按钮时开始新游戏"""
button_clicked = self.play_button.rect.collidepoint(mouse_pos)
if button_clicked and not self.stats.game_active:
# 重置游戏统计信息
self.stats.reset_stats()
self.stats.game_active = True
# 清空余下的外星人和子弹
self.aliens.empty()
self.bullets.empty()
# 创建一群新的外星人并让飞船居中
self._create_fleet()
self.ship.center_ship()
# 隐藏鼠标光标
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
"""响应按键"""
@ -156,6 +182,10 @@ class AlienInvasion:
bullet.draw_bullet()
self.aliens.draw(self.screen)
# 如果游戏处于非活动状态就绘制Play按钮
if not self.stats.game_active:
self.play_button.draw_button()
pygame.display.flip()
def _check_fleet_edges(self):
@ -189,6 +219,7 @@ class AlienInvasion:
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
"""检查是否有外星人到达了屏幕底端"""