ShipVSUFO
由python写的一个小游戏,飞船大战外星人。实现了能够闯关打分数的经典飞机射击游戏。玩法是玩家需要将ufo全部击落,获得更多的分数,否则将会被逼近的ufo撞击而被迫结束游戏。
一,分析
- 对象
飞船(ship),UFO(Alien), 子弹(bullet), 显示分数与关卡的面板(scoreboard), 用于开始游戏的按钮(button)。 - 功能
基本参数设置(settings),游戏状况(game_status),主函数(alien_invasion)以及主函数的函数(game_function)
二,编码实现
- 主函数(alien_invasion)
import sys
import pygame
from settings import Settings
from ship import Ship
from pygame.sprite import Group
import game_functions as gf
from alien import Alien
from game_status import GameStatus
from button import Button
from scoreboard import Scoreboard
def run_game():
pygame.init() ###初始化
ai_settings = Settings() ###设置类
screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) ###屏幕显示
ship = Ship(ai_settings,screen) ###飞船
pygame.display.set_caption("飞船大战UFO") ###标题
play_button = Button(ai_settings,screen,"Start Game") ###开始按钮
bullets = Group() ###子弹组
aliens = Group() ###外星人组
gf.create_fleet(ai_settings,ship,screen,aliens) ##创建外星人舰队
status = GameStatus(ai_settings) ###游戏状态
sb = Scoreboard(ai_settings,screen,status) ###分数板显示分数与关卡
while True:
gf.check_events(ai_settings,screen,ship,bullets,status,play_button,aliens)###事件监听
if status.game_active: ###若是游戏中
ship.update() ###飞船状态更新
gf.update_bullet(ai_settings,ship,screen,aliens,bullets,sb,status)### 子弹状态更新
gf.update_aliens(ai_settings,status,screen,ship,aliens,bullets)### 外星人更新
gf.update_screen(ai_settings,screen,ship,bullets,aliens,play_button,status,sb) ###屏幕更新重绘
run_game()
- 主函数中抽离的函数game_function:
import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep
def check_keydown_events(event,ai_settings,screen,ship,bullets):###监测按钮按下
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = True
elif event.key == pygame.K_SPACE:
new_bullet = Bullet(ai_settings,screen,ship)
bullets.add(new_bullet)
elif event.key == pygame.K_z:
sys.exit()
elif event.key == pygame.K_q:
ai_settings.bullet_width = 1000
elif event.key == pygame.K_w:
ai_settings.alien_speed_factor = 1
elif event.key == pygame.K_e:
ai_settings.alien_points = 500
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
elif event.key == pygame.K_UP:
ship.moving_up = False
elif event.key == pygame.K_DOWN:
ship.moving_down = False
def check_events(ai_settings,screen,ship,bullets,status,play_button,aliens):###监听各种事件
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_keyup_events(event,ai_settings,screen,ship,bullets)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x,mouse_y = pygame.mouse.get_pos()
check_play_button(status,play_button,mouse_x,mouse_y,aliens,bullets,ship,ai_settings,screen)
def check_play_button(status,play_button,mouse_x,mouse_y,aliens,bullets,ship,ai_settings,screen):###监听开始按键
if play_button.rect.collidepoint(mouse_x,mouse_y) and not status.game_active:
ai_settings.initialize_dynamic_settings()
pygame.mouse.set_visible(False)
status.reset_status()
status.game_active = True
status.level = 1
status.score = 0
aliens.empty()
bullets.empty()
create_fleet(ai_settings,ship,screen,aliens)
ship.center_ship()
def update_screen(ai_settings,screen,ship,bullets,aliens,play_button,status,sb):###屏幕的一切重绘,保证动态性
screen.fill(ai_settings.bg_color)
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
sb.show_score()
sb.show_level()
aliens.draw(screen)
if not status.game_active:
play_button.draw_button()
pygame.display.flip() ###重绘显示
def update_bullet(ai_settings,ship,screen,aliens,bullets,sb,status): ###
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:###子弹到头了,就删掉
bullets.remove(bullet)
check_bullet_alien_collisions(ai_settings,ship,screen,aliens,bullets,sb,status)
def check_bullet_alien_collisions(ai_settings,ship,screen,aliens,bullets,sb,status):###监听子弹与UFO碰撞
collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)
if collisions:###发生碰撞,一起消失
for aliens in collisions.values():
status.score += ai_settings.alien_points*len(aliens)
sb.prep_score()
if len(aliens)==0:###外星人为空,就重置游戏,并升级难度
bullets.empty()
ai_settings.increase_speed()
status.level += 1
sb.prep_level()
create_fleet(ai_settings,ship,screen,aliens)
def get_number_aliens_x(ai_settings,alien_width):###根据屏幕计算外星人数量
available_space_x = ai_settings.screen_width-2 * alien_width
number_aliens_x = int(available_space_x / (2 * alien_width))
return number_aliens_x
def 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,ship,screen,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 update_aliens(ai_settings,status,screen,ship,aliens,bullets):
check_fleet_edges(ai_settings, aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship,aliens):
ship_hit(ai_settings,status,screen,ship,aliens,bullets)
check_aliens_bottom(ai_settings,status,screen,ship,aliens,bullets)
def get_number_rows(ai_settings,ship_height,alien_height):###计算出外星人有多少行
available_space_y = (ai_settings.screen_height -(3 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_rows
def check_fleet_edges(ai_settings,aliens):
for alien in aliens.sprites():###监测舰队是否移动到屏幕的边境
if alien.check_edges():
change_fleet_direction(ai_settings,aliens)
break
def change_fleet_direction(ai_settings,aliens):###改变舰队方向
for alien in aliens.sprites():
alien.rect.y += ai_settings.fleet_drop_speed
ai_settings.fleet_direction *= -1
def ship_hit(ai_settings,status,screen,ship,aliens,bullets):###飞船被撞击后
if status.ships_left > 1:###生命还有
status.ships_left -= 1
aliens.empty()
bullets.empty()
create_fleet(ai_settings,ship,screen,aliens)
ship.center_ship()
sleep(0.5)
else: ###没有生命了
status.game_active = False
pygame.mouse.set_visible(True)
def check_aliens_bottom(ai_settings,status,screen,ship,aliens,bullets): ##监听外星UFO是否突破防线
screen_rect = screen.get_rect()
for alien in aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:###到达底部
ship_hit(ai_settings,status,screen,ship,aliens,bullets)
break
- 飞船类:
import pygame
class Ship():
def __init__(self,ai_settings,screen):###初始化
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx ###中心x与屏幕中心x一致
self.rect.bottom = self.screen_rect.bottom ### 底下与屏幕底下一致
### 移动状态
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
### 飞船坐标
self.center = float(self.rect.centerx)
self.centery = float(self.rect.centery)
def blitme(self):
###重绘
self.screen.blit(self.image,self.rect)
def update(self): ###坐标范围的判定,不能让飞船跳到外面去
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
elif self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
elif self.moving_up and self.rect.top > 0:
self.centery -= self.ai_settings.ship_speed_factor
elif self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.centery += self.ai_settings.ship_speed_factor
self.rect.centerx = self.center
self.rect.centery = self.centery
def center_ship(self): ###让飞船回到初始之地
self.center = self.screen_rect.centerx
self.centery = self.screen_rect.bottom - 1/2*(self.rect.bottom-self.rect.top)
- 外星人类:
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
def __init__(self,ai_settings,screen): ###初始化外星人的各个参数
super(Alien,self).__init__()
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/alien.bmp')
self.rect = self.image.get_rect()
self.rect.x = self.rect.width
self.rect.y = self.rect.height
self.x = float(self.rect.x)
def blitme(self):###屏幕绘制外星人模型
self.screen.blit(self.image,self.rect)
def update(self): ###更新UFO
self.x += self.ai_settings.alien_speed_factor*self.ai_settings.fleet_direction
self.rect.x = self.x
def check_edges(self):###检查是否超出屏幕
screen_rect = self.screen.get_rect()
if self.rect.right >= screen_rect.right:
return True
elif self.rect.left <= 0:
return True
return False
- 子弹类
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self,ai_settings,screen,ship):### 初始化
super(Bullet,self).__init__()
self.screen = screen
self.rect = pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update(self):###射出后,不断让纵坐标减少
self.y -= self.speed_factor
self.rect.y = self.y
def draw_bullet(self):###绘制子弹
pygame.draw.rect(self.screen,self.color,self.rect)
- 分数板类
import pygame.font
class Scoreboard():
def __init__(self, ai_settings, screen, stats):###分数板初始化
self.screen = screen
self.screen_rect = screen.get_rect()
self.ai_settings = ai_settings
self.stats = stats
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
self.prep_level()
def prep_score(self):###分数显示的模型,位置初始化
score_str = str(self.stats.score)
self.score_image = self.font.render(score_str, True, self.text_color,
self.ai_settings.bg_color)
self.score_rect = self.score_image.get_rect()
self.score_rect.right = self.screen_rect.right - 20
self.score_rect.top = 20
def show_score(self):###显示分数
self.screen.blit(self.score_image, self.score_rect)
def prep_level(self):###关卡显示模型,位置初始化
level_str = str(self.stats.level)
self.level_image = self.font.render(level_str,True,self.text_color,self.ai_settings.bg_color)
self.level_rect = self.level_image.get_rect()
self.level_rect.top = self.score_rect.top
self.level_rect.centerx = self.screen_rect.centerx
def show_level(self):###显示关卡
self.screen.blit(self.level_image,self.level_rect)
- 游戏状态类
class GameStatus():
def __init__(self, ai_settings):###游戏状态初始化
self.ai_settings = ai_settings
self.reset_status()
self.game_active = False
def reset_status(self):###重置游戏后,分数与关卡清零
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
- 游戏设置类
class Settings():
def __init__(self):
# 屏幕设置
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# 飞船设置
self.ship_limit = 1
# 子弹设置 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = 60, 60, 60
# 外星人设置
self.fleet_drop_speed = 10
self.speedup_scale = 2
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
- 按钮类
import pygame.font
class Button():
def __init__(self,ai_settings,screen,msg):###开始按钮初始化
self.screen = screen
self.screen_rect = screen.get_rect()
self.width,self.height = 200,50
self.button_color = (66,66,66)
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): ###输入内容
self.msg_img = self.font.render(msg,True,self.text_color,self.button_color)
self.msg_img_rect = self.msg_img.get_rect()
self.msg_img_rect.center = self.rect.center
def draw_button(self):###绘制
self.screen.fill(self.button_color,self.rect)
self.screen.blit(self.msg_img,self.msg_img_rect)
三,展示
-
点击Start Game开始游戏,最上方中间的是关卡,右边是分数
-
射击时,子弹击中UFO就一起出局
-
飞船撞上UFO失败