Python编程:《外星人入侵》
Posted Bruce_Liuxiaowei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python编程:《外星人入侵》相关的知识,希望对你有一定的参考价值。
Python编程:《外星人入侵》
Pygame是一组功能强大而有趣的的模块,可以用于管理图形、动画乃至声音,让你 能够更轻松地开发复杂的游戏。
《外星人入侵》游戏简介:
在游戏《外星人入侵》中, 玩家控制着一艘最初出现在屏幕底部中央的飞船。玩家可以使用箭头左右移动飞船,还可以使用空格键进行射击。游戏开始时,一群外星人出现在天空中,他们在屏幕中向下移动。玩家的任务时射杀这些外星人。玩家将所有外星人都消灭干净后,将出现一群新的外星人,他们移动的速度更快。只要有外星人撞到了玩家的飞船或到达了屏幕底部,玩家就损失一艘飞船。玩家损失三艘飞船后,游戏结束。
1.1 安装Pygame
本人的系统是macOS Monterey,要安装Pygame依赖的有些包,需要Home-brew。为安装Pygame依赖的库,请执行下面的命令:
(base) liuxiaowei@MacBook-Air ~ % brew install hg sdl sdl_image sdl_ttf
如果还想启用较高级的功能,如在游戏中包含声音, 可安装下面两个额外的库:
(base) liuxiaowei@MacBook-Air ~ % brew install sdl_mixer_portmidi
使用下面的命令来安装Pygame(如果你运行的是Python2.7, 请将pip3替换为pip ):
(base) liuxiaowei@MacBook-Air ~ % pip3 install --user hg+http://bitbucker.org/pygame/pygame
启动一个Python终端会话, 并导入Pygame以检查安装是否成功(如果你运行的是Python2.7, 请将python3替换为python):
(base) liuxiaowei@MacBook-Air ~ % python3
>>>import pygame
1.2开始游戏项目
游戏UML图如下所示:
1.2.1 创建alien_invasion.py
实现如下功能:
- 创建Pygame窗口以及响应用户输入
- 设置背景颜色
- 创建一个用于存储游戏统计信息的实例
- 创建一艘飞船,一个子弹编组和一个外星人编组
- 创建外星人群
- 监视键盘和鼠标事件
源码如下:
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from alien import Alien
from scoreboard import Scoreboard
from game_stats import GameStats
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)
# 创建一艘飞船,一个子弹编组和一个外星人编组
ship = Ship(ai_settings, screen)
bullets = Group()
aliens = Group()
# 创建一艘飞船
ship = Ship(ai_settings, screen)
#创建一个用于存储子弹的编组
bullets = Group()
# 创建外星人群
gf.create_fleet(ai_settings, screen, ship, aliens)
# 创建存储游戏统计信息的实例,并创建记分牌
# stats = GameStats(ai_settings)
# sb = Scoreboard(ai_settings, screen, stats)
# 开始游戏的主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
if stats.game_active:
ship.update()
gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
# bullets.update()
# gf.update_aliens(ai_settings, ship, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
# 在飞船和外星人后面重绘所有的子弹
for bullet in bullets:
bullet.draw_bullet()
# 监视键盘和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 每次循环时都重绘屏幕
screen.fill(ai_settings.bg_color)
ship.blitme()
# 让最近绘制的屏幕可见
pygame.display.flip()
run_game()
1.2.2 创建settings.py
实现功能如下:
- 创建名为Settings的类,用于将所有设置存储在一个地方
程序源码如下:
class Settings():
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的设置"""
# 屏幕设置
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# 飞船的设置
self.ship_speed_factor = 1.5
self.ship_limit = 3
# 子弹设置
self.bullet_speed_factor = 12
self.bullet_width = 3
self.bullet_height = 12
self.bullet_color = 60, 60, 60
self.bullets_allowed = 30000
# 外星人设置
self.alien_speed_factor = 1
self.fleet_drop_speed = 10
# fleet_direction为1表示向右转,为-1表示向左转
self.fleet_direction = 1
#以什么样的速度加快游戏节奏
self.speedup_scale = 1.1
# 加快游戏节奏的速度
self.score_scale = 1.5
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
"""初始化随游戏进行而变化的设置"""
self.ship_speed_factor = 1.5
self.bullet_speed_factor = 3
self.alien_speed_factor = 1
# fleet_direction为1表示向右; 为-1表示向左
self.fleet_direction = 1
# 记分
self.alien_points = 50
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)
1.2.3创建ship.py
实现功能如下:
- 负责管理飞船的大部分行为
源码如下:
"""
处理图像用矩形代替游戏图像元素,矩形是简单的几何形状
"""
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
# 加载飞船图像并获取其外接矩形, load返回surface
self.image = pygame.image.load('images/ship.bmp')
# rect是rectangle缩写, get_rect()获取相应的surface属性rect
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
# 在飞船的属性center中存储小数值
self.center = float(self.rect.centerx)
# 移动标志
self.moving_right = False
self.moving_left = False
def update(self):
"""根据移动标志调整飞船的位置"""
# 更新飞船的center值,而不是rect
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
# 根据self.center更新rect对象
self.rect.centerx = self.center
def blitme(self):
"""在指定位置绘制飞船"""
self.screen.blit(self.image, self.rect)
def center_ship(self):
"""让飞船在屏幕上居中"""
self.center = self.screen_rect.centerx
1.2.4 创建game_functions.py
实现功能如下:
- 游戏事件管理
程序源码如下:
from asyncio import events
# from fcntl import F_SEAL_SEAL
import imp
from re import A
import sys
from zoneinfo import available_timezones
from time import sleep
import pygame
from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
def check_events(ai_settings, screen, ship, bullets):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keydown_events(event, ai_settings, screen, ship, bullets)
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_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_bullet(ai_settings, screen, ship, bullets)
# 创建一颗子弹,并将其加入到编组bullets中
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
# 如果按q键,退出
elif event.key == pygame.K_q:
sys.exit()
def check_keyup_events(event, ai_settings, screen, ship, bullets):
"""响应松开"""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):
"""检查是否有外星人抵达屏幕底端"""
screen_rect = screen.get_rect()
for alien in aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
# 像飞船被撞到一样进行处理
ship_hit(ai_settings, stats, screen, ship, aliens, bullets)
break
# 检测子弹和外星人之间的碰撞
def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
"""响应子弹和外星人发生碰撞"""
# 删除发生碰撞的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if len(aliens) == 0:
# 删除现有的所有子弹, 并创建一个新的外星人群
bullets.empty()
create_fleet(ai_settings, screen, ship, aliens)
if len(aliens) == 0:
# 如果整群外星人都被消灭,就提高一个等级
bullets.empty()
ai_settings.increase_speed()
# 提高等级
stats.level += 1
sb.prep_level()
create_fleet(ai_settings, screen, ship, aliens)
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:
# 重置游戏设置
ai_settings.initialize_dynamic_settings()
# 隐藏光标
pygame.mouse.set_visible(False)
# 重置游戏统计信息
stats.reset_stats()
stats.game_active = True
# 重置记分牌图像
sb.prep_score()
sb.prep_high_score()
sb.prep_level()
sb.prep_ships()
# 清空外星人列表和子弹列表
aliens.empty()
bullets.empty()
def check_high_score(stats, sb):
"""检查是否诞生了新的最高分"""
if stats.score > stats.high_score:
stats.high_score = stats.score
sb.prep_high_score()
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 update_aliens(ai_settings, stats, screen, ship, aliens, bullets):
"""检查是否有外星人位于屏幕边缘,并更新整群外星人的位置"""
check_fleet_edges(ai_settings, aliens)
aliens.update()
# 检测外星人和飞船之间的碰撞
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, stats, screen, ship, aliens, bullets)
print("Ship hit!!!")
# 检测是否有外星人到达屏幕底端
check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)
def update_screen(ai_settings, screen, ship, aliens, bullets):
"""更新屏幕上的图案,并切换到新屏幕"""
# 每次循环时都重绘屏幕
screen.fill(ai_settings.bg_color)
# 在飞船和外星人后面重绘所有子弹
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
# alien.blitme()
aliens.draw(screen)
# 让最近绘制的屏幕可见
pygame.display.flip()
def update_bullets(ai_settings, screen, 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, ship, aliens, bullets)
# 检查是否有子弹击中了外星人
# 如果是这样,就删除相应的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if len(aliens) == 0:
#删除现有的子弹并新建一群外星人
bullets.empty()
create_fleet(ai_settings, screen, ship, aliens)
def ship_hit(ai_settings, stats, screen, ship, aliens, bullets):
"""响应被外星人撞到的飞船"""
# 将ships_left减1
stats.ships_left -= 1
# 清空外星人列表和子弹列表
aliens.empty()
bullets.empty()
# 创建一群新的外星人,并将飞船放到屏幕底端中央
create_fleet(ai_settings, screen, ship, aliens)
ship.center_ship()
# 暂停
sleep(0.5)
if stats.ships_left > 0:
# 将ships_left减1
stats.ships_left -= 1
# 更新记分牌
# sb.prep_ships()
else:
stats.game_active = False
def fire_bullet(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_aliens_x(ai_settings, alien_width):
"""计算每行可容纳多少个外星人"""
# 屏幕的宽度减掉2个外星人的宽度,因为两侧各空出一个外星人
available_space_x = ai_settings.screen_width - 2 * alien_width
# 外星人和空格间距是相等的, 所以除以2
number_aliens_x = int(available_space_x / (2 * alien_width))
return number_aliens_x
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.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_aliens_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)
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
1.2.5 创建bullet.py
<以上是关于Python编程:《外星人入侵》的主要内容,如果未能解决你的问题,请参考以下文章