Python的第三方库pygame开发的飞机大战
开发目录结构
游戏图片
1.背景图片
2.敌机图片
3.我方飞机图片
4.子弹图片
5.游戏结束背景图片
6.得分排行榜背景图片
说明:游戏只使用了两种音效,背景音乐和子弹击中敌机音乐;
代码实现
import sys
import random
import datetime
import pygame
pygame.init()
pygame.mixer.init()
# 常量
# 设置游戏窗口的长宽
SCREEN_RECT = pygame.Rect(0, 0, 480, 620)
# 时钟帧率
FPS = 60
# 设置敌机出现的定时器常量
CREATE_ENEMY_EVENT = pygame.USEREVENT
# 设置子弹发生的定时器
PLANE_FIRE_EVENT = pygame.USEREVENT 1
# 背景图片
bg = pygame.image.load("image/background.png")
# 敌机图片
enemy_img = pygame.image.load("image/enemy1.png")
# 我方飞机图片
plane_img = pygame.image.load("image/player1.png")
# 子弹图片
bullet_img = pygame.image.load("image/bullet.png")
# 游戏结束图片
game_over_img = pygame.image.load("image/gameover.png")
# 排行榜图片
ranking_img = pygame.image.load("image/ranking.png")
# 背景音效
# bg_sound=pygame.mixer.Sound("audio/bg_music.wav")
# 子弹击中敌机音效
bullet_enemy_sound = pygame.mixer.Sound("audio/bang.wav")
# 精灵类
class GameSprite(pygame.sprite.Sprite):
def __init__(self, image_name, speed=2):
super(GameSprite, self).__init__()
self.image = image_name
self.rect = self.image.get_rect()
self.speed = speed
def update(self):
self.rect.y = self.speed
# 背景精灵类
class Backgroud(GameSprite):
def __init__(self, is_alt=False):
super(Backgroud, self).__init__(bg)
if is_alt:
self.rect.y = -self.rect.height
def update(self):
super(Backgroud, self).update()
if self.rect.y >= SCREEN_RECT.height:
self.rect.y = -self.rect.height
# 敌机精灵类
class Enemy(GameSprite):
def __init__(self):
super(Enemy, self).__init__(enemy_img)
# 随机指定敌机的飞行速度
self.speed = random.randint(3, 5)
# 随机指定敌机的位置
self.rect.bottom = 0
self.rect.x = random.randint(0, SCREEN_RECT.width - self.rect.width)
def update(self):
super(Enemy, self).update()
# 敌机如果离开屏幕就销毁
if self.rect.y >= SCREEN_RECT.height:
self.kill()
# 飞机精灵类
class Plane(GameSprite):
def __init__(self):
super(Plane, self).__init__(plane_img, 0)
self.rect.centerx = SCREEN_RECT.centerx
self.rect.bottom = SCREEN_RECT.height - 30
# 子弹精灵组
self.bullet_group = pygame.sprite.Group()
def update(self):
self.rect.x = self.speed
if self.rect.left <= -10:
self.rect.left = -10
if self.rect.right >= SCREEN_RECT.width 10:
self.rect.right = SCREEN_RECT.width 10
# 发射子弹方法
def fire(self):
bullet = Bullet()
bullet.rect.centerx = self.rect.centerx
bullet.rect.y = self.rect.y
self.bullet_group.add(bullet)
# 子弹精灵类
class Bullet(GameSprite):
def __init__(self):
super(Bullet, self).__init__(bullet_img, -3)
def update(self):
super(Bullet, self).update()
if self.rect.bottom < 0:
self.kill()
# 文本类
class Text:
def __init__(self, font_size=32, pos_x=10, pos_y=10, text="", data=0):
# 文本
self.text = text
# 数据
self.data = data
# 字体样式
# self.font_css = font_css
# 字体大小
self.font_size = font_size
# 位置信息
self.pos_x = pos_x
self.pos_y = pos_y
def get_text(self):
content = str(self.data * 100) if self.text == "" else self.text
fonts_css = pygame.font.SysFont('SimHei', self.font_size)
self.text_content = fonts_css.render(content, True, (255, 255, 255))
self.text_rect = self.text_content.get_rect()
self.text_rect.x = self.pos_x
self.text_rect.y = self.pos_y
# 分数类
class Score(Text):
def __init__(self):
super().__init__()
def get_score(self):
super().get_text()
# 显示得分文本
class TextScore(Text):
def __init__(self, font_size=32, pos_x=10, pos_y=10, text="", data=0):
super(TextScore, self).__init__(font_size, pos_x, pos_y, text, data)
# 文本读写
class TextOperation:
def __init__(self):
self.text = 0
self.contents = []
# 写入文件
def write_text(self):
write_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
with open("score.txt", 'a', encoding='utf-8') as w:
w.write(str(self.text) " " write_time)
w.write('\n')
w.close()
# 读取文件
def read_text(self):
with open("score.txt", 'r', encoding='utf-8') as r:
self.contents = r.readlines()
r.close()
# 主类
class GameMain:
def __init__(self):
# 设置游戏窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
pygame.display.set_caption("飞机大战-wkx版")
# 设置时钟
self.clock = pygame.time.Clock()
# 创建精灵和精灵组
self.__create_sprite()
# 创建敌机出现的定时器,敌机1秒出现一个
pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
# 创建子弹发生定时器
pygame.time.set_timer(PLANE_FIRE_EVENT, 300)
# 背景音效
pygame.mixer.music.load("audio/bg_music.wav")
# 音效循环播放
pygame.mixer.music.play(-1, 0)
# 游戏结束标记
self.running = True
def __create_sprite(self):
# 背景精灵
bg1 = Backgroud()
bg2 = Backgroud(True)
self.bg_group = pygame.sprite.Group(bg1, bg2)
# 敌机精灵组
self.enemy_group = pygame.sprite.Group()
# 飞机精灵
self.plane = Plane()
self.plane_group = pygame.sprite.Group(self.plane)
self.sc = Score()
def start_game(self):
while self.running:
# self.screen.fill(0)
# 设置时钟帧率
self.clock.tick(FPS)
# 事件监听
self.__event_handler()
# 碰撞检测
self.__check_collide()
# 更新/绘制精灵和精灵组
self.__update_sprites()
# 更新屏幕显示
pygame.display.update()
# 统计最终得分
# print(self.sc.data)
final_score = TextOperation()
final_score.text = self.sc.data * 100
final_score.write_text()
# 游戏结束执行
while ~self.running:
self.__game_over()
# 事件监听
def __event_handler(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == CREATE_ENEMY_EVENT:
enemy = Enemy()
self.enemy_group.add(enemy)
if event.type == PLANE_FIRE_EVENT:
self.plane.fire()
# 控制飞机左右移动
plane_keys = pygame.key.get_pressed()
if plane_keys[pygame.K_LEFT]:
self.plane.speed = -2
if plane_keys[pygame.K_RIGHT]:
self.plane.speed = 2
# 碰撞检测
def __check_collide(self):
coll = pygame.sprite.groupcollide(self.plane.bullet_group, self.enemy_group, True, True)
if coll:
self.sc.data = 1
bullet_enemy_sound.play()
plane_over = pygame.sprite.groupcollide(self.plane_group, self.enemy_group, True, True)
if plane_over:
self.running = False
# 更新/绘制精灵和精灵组
def __update_sprites(self):
# 更新背景精灵
self.bg_group.update()
self.bg_group.draw(self.screen)
# 更新敌机精灵
self.enemy_group.update()
self.enemy_group.draw(self.screen)
# 更新飞机精灵
self.plane_group.update()
self.plane_group.draw(self.screen)
# 更新子弹精灵
self.plane.bullet_group.update()
self.plane.bullet_group.draw(self.screen)
# 得分
self.sc.get_score()
self.screen.blit(self.sc.text_content, self.sc.text_rect)
# 游戏结束
def __game_over(self):
# 绘制背景图片
self.screen.blit(game_over_img, (0, 0))
# 暂停背景音乐
pygame.mixer.music.stop()
# 绘制得分文本
text_score = TextScore(font_size=48, pos_x=120, pos_y=150, text="得分:")
text_score.get_text()
self.screen.blit(text_score.text_content, text_score.text_rect)
# 绘制分数
text_score = TextScore(font_size=48, pos_x=250, pos_y=150, data=self.sc.data)
text_score.get_text()
self.screen.blit(text_score.text_content, text_score.text_rect)
# 重新开始按钮
restart_button = TextScore(font_size=32, pos_x=180, pos_y=300, text="重新开始")
restart_button.get_text()
self.screen.blit(restart_button.text_content, restart_button.text_rect)
# 查看得分
look_score_button = TextScore(font_size=32, pos_x=180, pos_y=400, text="查看得分")
look_score_button.get_text()
self.screen.blit(look_score_button.text_content, look_score_button.text_rect)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
# 重新开始游戏
if (restart_button.text_rect.left <= event.pos[0] and restart_button.text_rect.right >= event.pos[0]
and restart_button.text_rect.top <= event.pos[1] and restart_button.text_rect.bottom >=
event.pos[1]):
self.running = True
start = GameMain()
start.start_game()
# 查看分数
if (look_score_button.text_rect.left <= event.pos[0] and look_score_button.text_rect.right >= event.pos[
0]
and look_score_button.text_rect.top <= event.pos[1] and look_score_button.text_rect.bottom >=
event.pos[1]):
self.__look_score()
# 查看分数
def __look_score(self):
look = TextOperation()
look.read_text()
score_list = []
for item in look.contents:
score_list.append(int(item.split(" ")[0]))
sss = sorted(score_list, reverse=True)[:5]
while True:
self.screen.blit(ranking_img, ranking_img.get_rect())
ranking = Text(font_size=48, pos_x=150, pos_y=100, text="排行榜")
ranking.get_text()
self.screen.blit(ranking_img, (0, 0))
self.screen.blit(ranking.text_content, ranking.text_rect)
for i in range(len(sss)):
ss = Text(font_size=32, pos_x=180, pos_y=180 50 * i, text=str(sss[i]))
ss.get_text()
self.screen.blit(ss.text_content, ss.text_rect)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if __name__ == '__main__':
start = GameMain()
start.start_game()
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved