小续
在之前我们已经实现了外星人入侵的基本功能,可是一直毫无目的玩,实在是没有成就感,添加计分板,可以有效记录自己的当前积分与等级,还可以有机会成就最高分,好好的吹一波不是,当然前面的那个bug在这节也已经解决了,话不多说,直接上代码!
创建新类scoreboard.py
用于显示最高分,等级,和余下的飞船数等
import pygame.ftfont
from pygame.sprite import Group
from ship import Ship
class Scoreboard():
"""显示的得分信息的类"""
def __init__(self,ai,screen,stats):
"""初始化显示得分设计的属性"""
self.screen=screen
self.screen_rect=screen.get_rect()
self.ai=ai
self.stats=stats
#显示得分信息时使用的字体设置
self.text_color=(30,30,30)
self.font=pygame.ftfont.SysFont(None,48)
#准备初始得分的图形
self.prep_score()
self.prep_high_score()
self.prep_level()
#飞船图标
self.prep_ships()
def prep_ships(self):
"""显示还有多少飞船"""
self.ships=Group()
for ship_num in range(self.stats.ships_left):
ship=Ship(self.ai,self.screen)
ship.rect.x=10+ship_num*ship.rect.width
ship.rect.y=10
self.ships.add(ship)
#绘制飞船等级水平
def prep_level(self):
#将等级转化为渲染的图像
self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai.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_score(self):
"""将得分转化为一副渲染的图像"""
#分数数值取千分位,且取整
rounded_score=int(round(self.stats.score,-1))
score_str="{:,}".format(rounded_score)
#score_str=str(self.stats.score)
self.score_image=self.font.render(score_str,True,self.text_color,self.ai.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):
"""将得分转化为一副渲染的图像"""
# 分数数值取千分位,且取整
rounded_score = int(round(self.stats.high_score, -1))
score_str = "{:,}".format(rounded_score)
# score_str=str(self.stats.score)
self.high_score_image = self.font.render(score_str, True, self.text_color, self.ai.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)
在这个类中,定义了当前分数与最高分,余下飞船数的相关函数与绘制方法
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=5
#ffleet_dirrection为1表示向右,-1xiangz向左
self.fleet_direction=1
#外星人点数提高速度
self.score_scale=1.5
#飞船设置
self.ship_speed_factor=1.5
self.ship_limit=3
#以什么样的速度加快游戏节奏
self.speedup_scale=1.1
self.inits_reset_settings()
#用于飞船碰撞死亡时,重置速度相关设置
def inits_reset_settings(self):
"""初始化随游戏进行而变化的设置"""
#初始化游戏的飞船子弹,外星人移动速度
self.ship_speed_factor=1.5
self.bullet_speed=30
self.alien_speed_factor=1
#外星人积分
self.alien_points=50
#fleet_directions左右方向标志
self.fleet_direction=1
#用于飞船射杀所有外星人后,游戏难度升级
def increase_speed(self):
"""提高速度设置,增加游戏难度"""
self.ship_speed_factor *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale
self.alien_points=int(self.alien_points*self.score_scale)
为了游戏的可玩性,我们添加了随等级而变化的飞船速度等属性,并增加了外星人积分,具体感受,还需要亲自体验一番
class GameState():
"""跟踪游戏的统计信息"""
def __init__(self,ai):
"""初始化统计信息"""
self.ai=ai
self.reset_stats()
#游戏一开始是非活动状态
self.game_active=False
#游戏最高分
self.high_score=0
def reset_stats(self):
"""初始化游戏运行期间可能变化的统计信息"""
self.ships_left=self.ai.ship_limit
#分数统计与等级水平
self.score=0
self.level=1
添加了分数统计与等级水平,游戏最高分属性
import pygame,time
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self,ai,screen):
"""初始化飞船并设置其初始位置"""
super().__init__()
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
self.rect.y=self.screen_rect.bottom-50
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)
基本没有变化,在开始导入精灵组魔块,Ship的继承类改为精灵,初始化中,重新加载一下父类精灵
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_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = 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
elif event.key == pygame.K_UP:
ship.moving_up = False
elif event.key == pygame.K_DOWN:
ship.moving_down = False
def check_events(ai, screen, stats,sb, play_button, ship, aliens, 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)
elif event.type==pygame.MOUSEBUTTONDOWN:
mouse_x,mouse_y=pygame.mouse.get_pos()
check_play_button(ai, screen, stats,sb,play_button, ship, aliens, bullets, mouse_x, mouse_y)
def check_play_button(ai,screen,stats,sb,play_button,ship,aliens,bullets,mouse_x,mouse_y):
"""在玩家单击play按钮是开始游戏"""
if not stats.game_active and play_button.rect.collidepoint(mouse_x,mouse_y):
#隐藏光标
pygame.mouse.set_visible(False)
#重置游戏统计信息
stats.reset_stats()
#重置游戏设置
ai.inits_reset_settings()
stats.game_active=True
#重置记分牌图像
sb.prep_high_score()
sb.prep_level()
sb.prep_score()
sb.prep_ships()
#清空外星人列表和子弹列表
aliens.empty()
bullets.empty()
#创建一群新的外星人,并让飞船居中
create_fleet(ai,screen,ship,aliens)
ship.center_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,stats,sb, ship, aliens, bullets,play_button):
screen.fill(ai_settings.bg_color)
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
aliens.draw(screen)
#显示得分
sb.show_score()
#如果游戏处于非活动状态,就绘制按钮play
if not stats.game_active:
play_button.draw_button()
pygame.display.flip()
def update_bullets(ai, screen, stats,sb,ship, aliens, bullets):
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
check_bullet_alien_collisions(ai, screen, stats,sb,ship, aliens, bullets)
def check_bullet_alien_collisions(ai, screen, stats,sb,ship, aliens, bullets):
#删除发生碰撞的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if collisions:
for aliens in collisions.values():
stats.score+=ai.alien_points*len(aliens)
sb.prep_score()
check_high_score(stats,sb)
if len(aliens) == 0:
bullets.empty()
#游戏难度升级
ai.increase_speed()
#提高等级
stats.level+=1
sb.prep_level()
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, sb,ship, aliens, bullets):
if stats.ships_left > 0:
# Decrement ships_left.
stats.ships_left -= 1
sb.prep_ships()
else:
stats.game_active = False
#光标显示
pygame.mouse.set_visible(True)
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, sb,ship, aliens, bullets):
check_fleet_edges(ai, aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai, stats, screen, sb,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+1):
create_alien(ai, screen, aliens, alien_number,
row_number)
#判断是否生成最高分
def check_high_score(stats,sb):
if stats.score>stats.high_score:
stats.high_score=stats.score
sb.prep_high_score()
更新了在各个函数中的新添加的计分板函数的使用,以及一些优化了游戏的处理事件,这部分改动比较多,好好看看,因为比较懒,就直接附源码了
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
from button import Button
#导入计分板
from scoreboard import Scoreboard
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
#实例化settings对象
ai=Settings()
#创建游戏窗口大小
screen=pygame.display.set_mode((ai.screen_width,ai.screen_height))
#创建游戏标题
pygame.display.set_caption("外星人大战")
#创建按钮
play_button=Button(ai,screen,"Play")
bg_color=(230,230,230)
#实例化飞船对象ship,传入屏幕实参
ship=Ship(ai,screen)
#创建一个用于存储游戏统计信息的实例,并创建计分板
stats=GameState(ai)
sb=Scoreboard(ai,screen,stats)
#创造一个用于存储子弹和外星人的编组
bullets=Group()
aliens=Group()
#创建外星人群
gf.create_fleet(ai,screen,ship,aliens)
#开始游戏的主循环
while True:
gf.check_events(ai, screen, stats, sb,play_button, ship, aliens, bullets)
if stats.game_active:
ship.update()
gf.update_bullets(ai,screen,stats,sb,ship,aliens,bullets)
gf.update_aliens(ai,stats,screen,sb,ship,aliens,bullets)
gf.update_screen(ai,screen,stats,sb,ship,aliens,bullets,play_button)
if __name__ == '__main__':
run_game()
一个外星人入侵的基本版本就算已经完成了,那么我们可以在基本版本上做一些修改与添加,要是一直玩游戏没有声音多不刺激,是不,对方太傻,要不要给对方增加发子弹的功能,增加游戏难度,要不要给自己留个后手,干点别的,嘿嘿….,那么就继续更新
基础版本的下载链接:https://download.csdn.net/download/jia666666/10573047