创建alien类
定义外星人的相关属性
alien.py
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""表示单个外星人的类"""
def __init__(self,ai,screen):
"""初始化外星人并设置起始位置"""
super().__init__()
self.screen=screen
self.ai=ai
#加载外星人图像
self.image=pygame.image.load('E:\外星人入侵\images\cliens.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)
import sys
import pygame
#导入设置类
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from alien import Alien
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
#实例化settings对象
ai=Settings()
#创建游戏窗口大小
screen=pygame.display.set_mode((ai.screen_width,ai.screen_height))
#创建游戏标题
pygame.display.set_caption("外星人大战")
bg_color=(230,230,230)
#实例化飞船对象ship,传入屏幕实参
ship=Ship(ai,screen)
#创造一个用于存储子弹和外星人的编组
bullets=Group()
aliens=Group()
gf.create_fleet(ai,screen,ship,aliens)
#开始游戏的主循环
while True:
#监视键盘和鼠标的事件
gf.check_evens(ai,screen,ship,bullets)
ship.update(ai, screen, ship, bullets)
gf.update_bullets(bullets)
gf.update_screen(ai,screen,ship,aliens,bullets)
# # 监视键盘和鼠标的事件
#
# gf.check_evens(ship)
# ship.update()
# gf.update_screen(ai, screen, ship)
if __name__ == '__main__':
run_game()
创建了外星人编组,添加外星人群创建函数并主动触发,屏幕更新函数小改动
game_functions.py
创建外星人群的相关函数
import sys
import pygame
from bullet import Bullet
from alien import Alien
def check_keydown_event(event,ai,screen,ship,bullets):
if event.key == pygame.K_RIGHT:
# 向右移动飞船
ship.moving_right = True
elif event.key==pygame.K_q:
sys.exit()
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:
#创建一个用于存储子弹的编组
ship.bullet_fire=True
fire_bullet(ai, screen, ship, bullets)
def check_keyup_event(event,ship):
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
elif event.key==pygame.K_SPACE:
#创建一个用于存储子弹的编组
ship.bullet_fire=False
def check_evens(ai,screen,ship,bullets):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#检测是否有按键按下
elif event.type==pygame.KEYDOWN:
check_keydown_event(event,ai,screen,ship,bullets)
elif event.type==pygame.KEYUP:
check_keyup_event(event, ship)
def fire_bullet(ai, screen, ship, bullets):
if ship.bullet_fire and len(bullets) < ai.bullet_nums:
new_bullet = Bullet(ai, screen, ship)
bullets.add(new_bullet)
def update_screen(ai,screen,ship,aliens,bullets):
"""每次更新屏幕上的图像,并切换到新屏幕"""
# 背景填充颜色
screen.fill(ai.bg_color)
#将飞船绘制到屏幕上
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
#调用draw时,自动绘制编组的每个元素,绘制位置,有元素的属性rect决定
aliens.draw(screen)
#绘制所有字弹
# 让最近绘制的屏幕可见,否则是看不见的
pygame.display.flip()
def update_bullets(bullets):
#子弹更新
bullets.update()
# 删除消失的子弹
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
def get_alien_num_x(ai,alien_width):
"""创建外星人群"""
#创建一个外星人,并计算一行可以容纳多少个外星人
available_space_x=ai.screen_width-(2*alien_width)
alien_num_x=int(available_space_x/(2*alien_width))
return alien_num_x
def get_alien_num_y(ai,ship_height,alien_height):
"""创建外星人群"""
#创建一个外星人,并计算一列可以容纳多少个外星人
available_space_y=ai.screen_height-(3*alien_height)-ship_height
alien_num_y=int(available_space_y/(2*alien_height))
return alien_num_y
def create_alien(ai,screen,aliens,alien_number_x,alien_number_y):
#创键一外星人,设置外星人的初始rect.x的值,并加入外星人组
alien = Alien(ai, screen)
alien_width = alien.rect.width
#外星人的初始坐标x,y
alien.rect.x = alien_width + 2 * alien_width * alien_number_x
alien.rect.y = alien.rect.height + 2 * alien.rect.height * alien_number_y
aliens.add(alien)
def create_fleet(ai,screen,ship,aliens):
#实例化一个外星人
alien = Alien(ai, screen)
#计算一行最多可以有多少外星人
alien_num_x=get_alien_num_x(ai,alien.rect.width)
alien_num_y = get_alien_num_y(ai,ship.rect.height,alien.rect.height)
for num_y in range(alien_num_y):
for num_x in range(alien_num_x+1):
#创建一行外星人
create_alien(ai,screen,aliens,num_x,num_y)
增加多个相关外星人的函数,比如外星人每行列的最大容纳数,以及创建外星人与绘制外形人组
外星人默认向右移动,检测是否碰到屏幕边缘,是则向下移动,然后向左移动 继续判
settings.py设置外星人的相关属性以及定义子弹的速度等属性
class Settings():
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的设置"""
#屏幕设置
self.screen_width=800
self.screen_height=600
self.bg_color=(230,230,230)
#子弹设置
self.bullet_speed=3
self.bullet_widths=3
self.bullet_heights=15
self.bullet_color=60,60,60
self.bullet_nums=300
#外星人的设置
self.alien_speed_factor=1
self.fleet_drop_speed=10
#ffleet_dirrection为1表示向右,-1xiangz向左
self.fleet_direction=1
#飞船设置
self.ship_speed_factor=1.5
self.ship_limit=3
添加外星人的相关属性设置
import sys
from time import sleep
import pygame
from bullet import Bullet
from alien import Alien
def check_keydown_events(event, ai, 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, screen, ship, bullets)
elif event.key == pygame.K_q:
sys.exit()
def check_keyup_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai, 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, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def fire_bullet(ai, screen, ship, bullets):
if len(bullets) < ai.bullet_nums:
new_bullet = Bullet(ai, screen, ship)
bullets.add(new_bullet)
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()
aliens.draw(screen)
pygame.display.flip()
def update_bullets(ai, screen, ship, aliens, bullets):
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
check_bullet_alien_collisions(ai, screen, ship, aliens, bullets)
def check_bullet_alien_collisions(a, screen, ship, aliens, bullets):
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if len(aliens) == 0:
bullets.empty()
create_fleet(ai, screen, ship, aliens)
def check_fleet_edges(ai, aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai, aliens)
break
def change_fleet_direction(ai, aliens):
for alien in aliens.sprites():
alien.rect.y += ai.fleet_drop_speed
ai.fleet_direction *= -1
def ship_hit(ai, stats, screen, ship, aliens, bullets):
if stats.ships_left > 0:
# Decrement ships_left.
stats.ships_left -= 1
else:
stats.game_active = False
aliens.empty()
bullets.empty()
create_fleet(ai, screen, ship, aliens)
ship.center_ship()
# Pause.
sleep(0.5)
def check_aliens_bottom(ai, 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, stats, screen, ship, aliens, bullets)
break
def update_aliens(ai, stats, screen, ship, aliens, bullets):
check_fleet_edges(ai, aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai, stats, screen, ship, aliens, bullets)
check_aliens_bottom(ai, stats, screen, ship, aliens, bullets)
def get_number_aliens_x(ai, alien_width):
available_space_x = ai.screen_width - 2 * alien_width
number_aliens_x = int(available_space_x / (2 * alien_width))
return number_aliens_x
def get_number_rows(ai, ship_height, alien_height):
available_space_y = (ai.screen_height -
(3 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_rows
def create_alien(ai, screen, aliens, alien_number, row_number):
alien = Alien(ai, 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, screen, ship, aliens):
alien = Alien(ai, screen)
number_aliens_x = get_number_aliens_x(ai, alien.rect.width)
number_rows = get_number_rows(ai, ship.rect.height,
alien.rect.height)
for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
create_alien(ai, screen, aliens, alien_number,
row_number)
更新外星人的位置添加方向移动,以及子弹与外星人的碰撞检测,创建新的外星人群等函数
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('E:\外星人入侵\images\cliens.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 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
def update(self):
self.x += (self.ai_settings.alien_speed_factor *
self.ai_settings.fleet_direction)
self.rect.x = self.x
def blitme(self):
self.screen.blit(self.image, self.rect)
检测外星人是否碰到屏幕边缘
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameState
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
#实例化settings对象
ai=Settings()
#创建游戏窗口大小
screen=pygame.display.set_mode((ai.screen_width,ai.screen_height))
#创建游戏标题
pygame.display.set_caption("外星人大战")
bg_color=(230,230,230)
#实例化飞船对象ship,传入屏幕实参
ship=Ship(ai,screen)
#创建一个用于存储游戏统计信息的实例
stats=GameState(ai)
#创造一个用于存储子弹和外星人的编组
bullets=Group()
aliens=Group()
gf.create_fleet(ai,screen,ship,aliens)
#开始游戏的主循环
while True:
if stats.game_active:
gf.check_events(ai,screen,ship,bullets)
ship.update()
gf.update_bullets(ai,screen,ship,aliens,bullets)
gf.update_aliens(ai,stats,screen,ship,aliens,bullets)
gf.update_screen(ai,screen,ship,aliens,bullets)
if __name__ == '__main__':
run_game()
创建用于统计信息的新文件game_stats.py
class GameState():
"""跟踪游戏的统计信息"""
def __init__(self,ai):
"""初始化统计信息"""
self.ai=ai
self.reset_stats()
#游戏启动时是活动状态
self.game_active=True
def reset_stats(self):
"""初始化游戏运行期间可能变化的统计信息"""
self.ships_left=self.ai.ship_limit
ship.py
import pygame,time
from game_functions import fire_bullet
class Ship():
def __init__(self,ai,screen):
"""初始化飞船并设置其初始位置"""
self.screen=screen
self.ai=ai
#加载飞船图像
self.image=pygame.image.load('images\ship.bmp')
#获取飞船图像的长宽尺寸
self.rect=self.image.get_rect()
#获取游戏屏幕的尺寸
self.screen_rect=screen.get_rect()
#将每艘新飞船放在屏幕底部的中央
#飞船的x坐标=屏幕的x中间位置坐标
self.rect.centerx=self.screen_rect.centerx
#飞船的y坐标=屏幕的底部Y值
self.rect.bottom=self.screen_rect.bottom
#飞船移动标志
self.moving_right=False
self.moving_left =False
self.moving_down = False
self.moving_up = False
def center_ship(self):
"""让飞船在屏幕上居中"""
self.rect.centerx = self.screen_rect.centerx
def update(self):
"""根据移动标志调整飞船的位置"""
#更新飞船的center值而不是rect
#
if self.moving_right and self.rect.right < self.screen_rect.right:
self.rect.centerx += 1
if self.moving_left and self.rect.left > 0:
self.rect.centerx -= 1
if self.moving_up and self.rect.top > self.screen_rect.top:
self.rect.centery -= 1
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.rect.centery += 1
self.rect.centerx = self.rect.centerx
self.rect.centery = self.rect.centery
def blitme(self):
"""指定位置绘制飞船"""
#blit(图像,图像绘制的位置坐标)
self.screen.blit(self.image,self.rect)
bullets.py
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""一个对飞船发射的子弹进行管理的类."""
def __init__(self, ai, screen, ship):
"""在飞船所在位置创建一个子弹对象."""
super().__init__()
self.screen = screen
# 在0.0坐标处创建一个表示子弹的矩形,在设置正确的位置
self.rect = pygame.Rect(0, 0, ai.bullet_widths,ai.bullet_heights)
#子弹的x坐标为飞船的x坐标,子弹的头为飞船的头,形象表示子弹从飞船发射
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
# 存储用小数表示的子弹位置
self.y = float(self.rect.y)
#子弹颜色与速度设置
self.color = ai.bullet_color
self.speed_factor = ai.bullet_speed
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)