14.1 添加 Play 按钮
要添加 Play 按钮,说明游戏一开始必须处于非活动状态,按 Play 按钮来激活游戏 修改 game_stats.py
class GameStats:
'''跟踪游戏的统计信息'''
def __init__(self, ai_game):
'''初始化统计信息'''
self.settings = ai_game.settings
self.reset_stats()
self.game_active = False
def reset_stats(self):
'''初始化游戏在运行中可能改变的统计信息'''
self.ships_left = self.settings.ship_limit
14.1.1 创建Button类
pygame 没有内置创建按钮的方法,我们用画实心矩形的方法创建标签 新建一个 button.py
import pygame.font
class Button:
def __init__(self, ai_game, msg):
'''初始化按钮的属性'''
self.screen = ai_game.screen
self.screen_rect = self.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)
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect.center = self.screen_rect.center
self._pre_msg(msg)
def _pre_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)
14.1.2 在屏幕上绘制按钮
在alien_invasion.py 中修改程序
- 导入 Button 类
- 在 _ _ init _ _()方法中创建按钮
- 在 _update_screen()中调用 draw_button()
方法 run_game() 要先执行一次 _update_screen(),不然会出现黑屏,即无法启动游戏
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行效果如下图:
14.1.3 开始游戏
使用 play 按钮开始游戏,需要监控鼠标左键,当左键单击按钮时,标志位 self.stats.game_active 修改为True,游戏开始 修改 的代码
- 在 alien_invasion.py方法中新增:监控左键,若左键单击按钮,则重新开始游戏
- 重新开始游戏封装成一个方法,在_check_event() 监控左键状态中调用
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
if self.play_button.rect.collidepoint(mouse_pops):
self.stats.game_active = True
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发现Play按钮可以控制游戏的开始了
14.1.4 重置游戏
现在我们的代码只处理了第一次单击Play按钮的情况,而没有处理游戏结束弹出play按钮会怎么样(这种情况只会只执行一遍,失败后就跳到起始画面) 每次单击Play,我们要重置统计信息,删除现有外星人和子弹,创建新的外星人和飞船 在alien_invasion.py 中修改 _check_play_button(self, mouse_pops) 方法
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
if self.play_button.rect.collidepoint(mouse_pops):
self.stats.reset_stats()
self.stats.game_active = True
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,可以正常执行
14.1.5 将Play按钮切换到非活动状态
此时,有一个问题:即使Play按钮看不到,但只要在该区域单击鼠标左键,仍然会让游戏重置 为修复该问题,我们可以让单击左键和标志位在非活动状态同时成立时,才能单击 Play 按钮 修改alien_invasion.py 中的 _check_play_button(self, mouse_pops) 方法
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
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._creat_fleet()
self.ship.center_ship()
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发现问题已经完美修复,只要游戏开始,就算鼠标单击 Play 按钮区域,游戏也不会重置
14.1.6 隐藏鼠标光标
在游戏未开始时,鼠标可见(因为要单击 Play开始游戏),游戏开始后,鼠标就多余了,我们需要将其隐藏起来 在alien_invasion.py 中修改代码
- 在 _check_play_button(self, mouse_pops) 方法中,开始游戏后,隐藏鼠标
- 在 _ship_hit(self) 方法中,结束游戏,鼠标可见
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
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._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序发现:当开始游戏,鼠标隐藏,当游戏失败,鼠标出现
14.2 提高等级
在玩家消灭完一波外星人后(完成当前难度),需要提高游戏难度
14.2.1 修改速度设置
我们将游戏设置分为静态设置和动态设置两组,静态设置还在 _ _init _ _()中初始化, 动态设置放在一个新的方法内
- 在settings.py 中,将原设置分成俩类,动态设置存储方法 initialize_dynamic_settings(self) 为新建
- 新建一个动态提高难度方法increase_speed(self)
- 在 alien_invasion.py 中,当外星人全部被消灭,_check_bullet_alien_collisions(self) 调用方法settings.increase_speed() ,以提高难度
class Settings:
'''存储游戏中所有设置的类'''
def __init__(self):
'''初始化游戏设置'''
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullet_allowed = 3
self.fleet_drop_speed = 10
self.speedup_scale = 1.1
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
'''随着游戏进度推进,需要变化的设置'''
self.ship_speed = 2
self.bullet_speed = 1.5
self.alien_speed = 1.0
self.fleet_drection = 1
def increase_speed(self):
'''提高速度'''
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
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._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发现消灭完一波外星人后,新出现的外星人速度明显加快(如果觉得效果不明显,可将settings.py 中的 self.speedup_scale = 1.1 改成 1.5)
14.2.2 重置速度
此时出现一个问题,当游戏失败后,单机Play按钮开始,发现游戏的是在上次失败的速度基础上开始的,这与我们的预期不符(我们预期应该是重新开始,包括飞船的移动速度) 我们需要在alien_invasion.py 中 _check_play_button(self, mouse_pops)中调用settings.initialize_dynamic_settings() 方法,重置游戏设置
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序发现,当游戏失败,单击 Play 按钮,游戏恢复到最初始的简单难度
14.3 记分
分数是统计信息,因此在game_stats.py 中的类 GameStats 中新增一个 score 属性
14.3.1 显示得分
创建一个新的py文件:scoreboard.py,并在里面创建显示得分的类
import pygame.font
class Scoreboard:
'''显示得分信息的类'''
def __init__(self, ai_game):
'''初始化显示得分涉及的属性'''
self.screen =ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
def prep_score(self):
'''将得分渲染为一幅图像'''
score_str = str(self.stats.score)
self.score_image = self.font.render(score_str, True, self.text_color, self.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 show_score(self):
'''在屏幕显示得分'''
self.screen.blit(self.score_image, self.score_rect)
14.3.2 创建记分牌
在 alien_invasion.py 中修改代码
- 导入Scorboard类
- 在_ _ init _ _ () 方法中创建Scorboard实例
- 在 _update_screen()方法中将记分牌绘制到屏幕上
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
运行程序,发现屏幕左上角出现一个记分牌,显示 0 ,如下图:
14.3.3 在外星人被消灭时更新得分
首先确定击落一个外星人多少分,在settings.py 的 initialize_dynamic_settings() 中设置击落一个外星人为50分
class Settings:
'''存储游戏中所有设置的类'''
def __init__(self):
'''初始化游戏设置'''
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullet_allowed = 3
self.fleet_drop_speed = 10
self.speedup_scale = 1.5
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
'''随着游戏进度推进,需要变化的设置'''
self.ship_speed = 2
self.bullet_speed = 1.5
self.alien_speed = 1.0
self.fleet_drection = 1
self.alien_points = 50
def increase_speed(self):
'''提高速度'''
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
在 alien_invasion.py 的 _check_bullet_alien_collisions(self) 中,更新得分
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if collisions:
self.stats.score += self.settings.alien_points
self.sb.prep_score()
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序发现,消灭外星人,左上角的记分牌就会更新,如下图:
14.3.4 重置得分
现在有一个问题,在第二次游戏开始时,外星人被射杀,期间一直显示的是上一次的得分 为修复这个问题,可以在喀什游戏时生成得分,即在 alien_invasion.py 的_check_play_button() 中,调用sb.prep_score()函数
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if collisions:
self.stats.score += self.settings.alien_points
self.sb.prep_score()
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.sb.prep_score()
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序发现,只要重新按下 Play 按钮,右上角的分数会立刻变为0
14.3.5 将消灭的每个外星人都记入得分
上述代码可能会出现一颗子弹击中两个外星人,但只会计算一个外星人的分数 比如,我们在设置中将子弹宽设置为300 执行程序,发现,虽然击中了两个外星人,但只得到50分,与预期不符,见下图:
完善 alien_invasion.py 的_check_bullet_alien_collisions 代码,修复上述错误,因为在碰撞检查的字典中,子弹是键,外星人是对应的值,且是一个列表,只要准确计算列表的个数即可
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if collisions:
for aliens in collisions.values():
self.stats.score += self.settings.alien_points * len(aliens)
self.sb.prep_score()
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.sb.prep_score()
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发现一颗子弹,消灭3个外星人,得分为150分,满足预期,见下图: (程序测试完成,将子弹宽度改回3)
14.3.6 提高分数
鉴于玩家每提高一个等级,游戏难度增加,所以消灭外星人的得分也应该相应提高 在 settings.py 中修改,增加分数提高倍数和计算公式
class Settings:
'''存储游戏中所有设置的类'''
def __init__(self):
'''初始化游戏设置'''
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullet_allowed = 3
self.fleet_drop_speed = 10
self.speedup_scale = 1.5
self.score_scale = 1.5
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
'''随着游戏进度推进,需要变化的设置'''
self.ship_speed = 2
self.bullet_speed = 1.5
self.alien_speed = 1.0
self.fleet_drection = 1
self.alien_points = 50
def increase_speed(self):
'''提高速度'''
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale)
print(self.alien_points)
执行效果如下图: 发现终端窗口中显示的击落外星人分数确实随难度提高而提高 (print()函数是测试用,测试完需要隐藏) 即改为 “# print(self.alien_points)”
13.3.7 舍入得分
将游戏得分整圆成10的整数倍,并在显示时使用千位分隔符 在 scoreboard.py 中修改
import pygame.font
class Scoreboard:
'''显示得分信息的类'''
def __init__(self, ai_game):
'''初始化显示得分涉及的属性'''
self.screen =ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
def prep_score(self):
'''将得分渲染为一幅图像'''
rounded_score = round(self.stats.score, -1)
score_str = f"{rounded_score:,}"
self.score_image = self.font.render(score_str, True, self.text_color, self.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 show_score(self):
'''在屏幕显示得分'''
self.screen.blit(self.score_image, self.score_rect)
执行效果如下图所示:
14.3.8 最高得分
最高得分纪录要存储起来,并记录
- 任何情况都不应该重置最高得分,在 game_stats.py 中初始化high_score
- 最高得分显示在屏幕的中间,与当前得分区分,在 scoreboard.py 中修改,并新增方法prep_high_score(self)
- 在scoreboard.py 的 show_score()方法中调用并显示最高分
- 在 scoreboard.py 中新增一个方法 check_high_score(self),检查是否产生最高分,是则更新最高分
- 在alien_invasion.py 的 _check_bullet_alien_collisions 中,调用是否产生最高分
class GameStats:
'''跟踪游戏的统计信息'''
def __init__(self, ai_game):
'''初始化统计信息'''
self.settings = ai_game.settings
self.reset_stats()
self.game_active = False
self.high_score = 0
def reset_stats(self):
'''初始化游戏在运行中可能改变的统计信息'''
self.ships_left = self.settings.ship_limit
self.score = 0
import pygame.font
class Scoreboard:
'''显示得分信息的类'''
def __init__(self, ai_game):
'''初始化显示得分涉及的属性'''
self.screen =ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
self.prep_high_score()
def prep_score(self):
'''将得分渲染为一幅图像'''
rounded_score = round(self.stats.score, -1)
score_str = f"{rounded_score:,}"
self.score_image = self.font.render(score_str, True, self.text_color, self.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 = f"{high_score:,}"
self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.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 show_score(self):
'''在屏幕显示得分'''
self.screen.blit(self.score_image, self.score_rect)
self.screen.blit(self.high_score_image, self.high_score_rect)
def check_high_score(self):
'''检查是否诞生了新的最高得分'''
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
执行程序,发现获得的最高得分,重新按Paly按钮,发现最高分可以保留,见下图:
14.3.9 显示等级
可以在游戏中显示当前游戏关卡的等级
- 在 game_stats.py 的 reset_stats(self) 方法中初始化游戏等级
- 在 scoreboard.py 中新建一个方法 prep_level(self) ,并在 _ _ init _ _ ()中初始化
- 在 scoreboard.py 中的 show_score(self) 方法中 显示游戏等级
- 在 alien_invasion.py 的 _check_bullet_alien_collisions(self) 中,外星人被全部消灭,等级+1
- 为确保游戏更新等级图像,在alien_invasion.py 的 _check_play_button() 中也要调用
class GameStats:
'''跟踪游戏的统计信息'''
def __init__(self, ai_game):
'''初始化统计信息'''
self.settings = ai_game.settings
self.reset_stats()
self.game_active = False
self.high_score = 0
def reset_stats(self):
'''初始化游戏在运行中可能改变的统计信息'''
self.ships_left = self.settings.ship_limit
self.score = 0
self.level = 1
import pygame.font
class Scoreboard:
'''显示得分信息的类'''
def __init__(self, ai_game):
'''初始化显示得分涉及的属性'''
self.screen =ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
self.prep_high_score()
self.prep_level()
def prep_score(self):
'''将得分渲染为一幅图像'''
rounded_score = round(self.stats.score, -1)
score_str = f"{rounded_score:,}"
self.score_image = self.font.render(score_str, True, self.text_color, self.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 = f"{high_score:,}"
self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.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 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)
def check_high_score(self):
'''检查是否诞生了新的最高得分'''
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
def prep_level(self):
'''将等级渲染为图像'''
level_str = str(self.stats.level)
self.level_image = self.font.render(level_str, True, self.text_color, self.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
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if collisions:
for aliens in collisions.values():
self.stats.score += self.settings.alien_points * len(aliens)
self.sb.prep_score()
self.sb.check_high_score()
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
self.stats.level += 1
self.sb.prep_level()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.sb.prep_score()
self.sb.prep_level()
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发现右上角有当前关卡等级,重点Play按钮,游戏除保留最高分外,其余重新开始,见下图:
14.3.10 显示余下的飞船数
本节将完成“当前玩家还有多少飞船可用”功能
- 在 ship.py中,导入Sprite 类,并让类 Ship 继承
- 在 scoreboard.py 中,导入类Group和类Ship,修改类Scoreboard,以创建飞船组
- 在 scoreboard.py中,新建一个方法prep_ships(),显示还余下多少艘飞船
- 在 scoreboard.py中,在show_score()中展示绘制的飞船
- 在alien_invasion.py 的_check_play_button()中调用sb.prep_ships()
- 在 alien_invasion.py的_ship_hit()时调用sb.prep_ships()更新图像
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
'''管理飞船的类'''
def __init__(self, ai_game):
'''初始化飞船,并设置其初始位置'''
super().__init__()
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.settings = ai_game.settings
self.image = pygame.image.load(r"images/ship.bmp")
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
self.x = float(self.rect.x)
self.moving_right = False
self.moving_left = False
def update(self):
'''根据移动标记状态调整调整飞船位置'''
if self.moving_right and self.rect.right < self.screen_rect.right:
self.rect.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.rect.x -= self.settings.ship_speed
def blitme(self):
'''在指定位置绘制飞船'''
self.screen.blit(self.image, self.rect)
def center_ship(self):
'''让飞船在屏幕底部居中显示'''
self.rect.midbottom = self.screen_rect.midbottom
self.x = float(self.rect.x)
import pygame.font
from pygame.sprite import Group
from ship import Ship
class Scoreboard:
'''显示得分信息的类'''
def __init__(self, ai_game):
'''初始化显示得分涉及的属性'''
self.ai_game = ai_game
self.screen =ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.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 = f"{rounded_score:,}"
self.score_image = self.font.render(score_str, True, self.text_color, self.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 = f"{high_score:,}"
self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.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 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)
def check_high_score(self):
'''检查是否诞生了新的最高得分'''
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
def prep_level(self):
'''将等级渲染为图像'''
level_str = str(self.stats.level)
self.level_image = self.font.render(level_str, True, self.text_color, self.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_game)
ship.rect.x = 10 + ship_number * ship.rect.width
ship.rect.y = 10
self.ships.add(ship)
import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien
from settings import Settings
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
class AlienInvasion:
'''管理游戏资源和行为的类'''
def __init__(self):
'''初始化游戏并创建游戏资源'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
'''
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height'''
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._creat_fleet()
self.play_button = Button(self, "Play")
def run_game(self):
'''开始游戏的主循环'''
while True:
self._check_event()
self._update_screen()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
pygame.time.delay(5)
pygame.display.flip()
def _creat_fleet(self):
'''创建外星人群'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien_width = alien.rect.width
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
ship_height = self.ship.rect.height
available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_width)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x+1):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
'''创建外星人并将其放在当前行'''
alien = Alien(self)
alien_width, alien_height = alien.rect.size
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
self.aliens.add(alien)
def _check_fleet_edges(self):
'''有外星人到达边缘时,采取措施'''
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
'''将整群外星人下移,并改变左右移动的方向'''
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_drection *= -1
def _update_bullets(self):
'''更新子弹的位置并删除消失的子弹'''
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
'''检查子弹和外星人碰撞,并删除碰撞元素'''
collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
if collisions:
for aliens in collisions.values():
self.stats.score += self.settings.alien_points * len(aliens)
self.sb.prep_score()
self.sb.check_high_score()
if not self.aliens:
self.bullets.empty()
self._creat_fleet()
self.settings.increase_speed()
self.stats.level += 1
self.sb.prep_level()
def _update_aliens(self):
'''检查是否有外星人在屏幕边缘,并更新所有外星人位置'''
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom()
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pops = pygame.mouse.get_pos()
self._check_play_button(mouse_pops)
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_play_button(self, mouse_pops):
'''玩家单击Play按钮开始游戏'''
button_clicked = self.play_button.rect.collidepoint(mouse_pops)
if button_clicked and (not self.stats.game_active):
self.settings.initialize_dynamic_settings()
self.stats.reset_stats()
self.stats.game_active = True
self.sb.prep_score()
self.sb.prep_level()
self.sb.prep_ships()
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
'''创建一颗子弹,并加入编组bullets中'''
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_screen(self):
'''更新屏幕上的图像,并更新到新屏幕'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
self.sb.show_score()
if not self.stats.game_active:
self.play_button.draw_button()
def _ship_hit(self):
'''响应飞船被外星人撞到'''
self.aliens.empty()
self.bullets.empty()
self._creat_fleet()
self.ship.center_ship()
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
self.sb.prep_ships()
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _check_aliens_bottom(self):
'''检查是否有外星人到达屏幕底部'''
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
执行程序,发下左上角显示可用飞船数量,当失败一次,就去掉一个飞船,如下图:
左上角表示生命的飞机太大,可以考虑用适当的方法让其变小
14.4小结
略
|