代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
"""
@Author: 芮芪懿 QQ1849433491
@Project->File: pygame_train -> game_main.py
@IDE:PyCharm
@File: game_main.py
@Datetime: 2021/7/9 16:24
"""
from game_sprites import *
from pygame.sprite import Group
from game_sound import GameSound
from game_public import *
from file_op import *
FRAME_RATE = 60
FIRE_EVENT = pygame.USEREVENT
CREATE_ENEMY_EVENT = FIRE_EVENT + 1
SUPER_FIRE_EVENT = CREATE_ENEMY_EVENT + 1
isSuperFire = False
enemyMoveSpeed = 3 # 敌机移动速度 TODO 随游戏分数变化移动速度
playerScore = 0 # 玩家分数
WHITE = (255, 255, 255)
enemyHitedScore = 100
class PlaneGameMain:
"""
@Author: 芮芪懿
@Datetime: 2021/7/9 16:35
飞机大战游戏主体类
"""
def __init__(self):
init_pygame()
# self.gameFont = pygame.font.SysFont("微软软黑", 30)
self.gameFont = pygame.font.SysFont("Arial", 30)
# self.gameFont = pygame.font.Font("resources/font/sans.ttf", 30)
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
self.gameSounds = GameSound()
self.isSuperFire = False
self.isFirstAppended = False
self.isNewRecord = False
self.rankList = []
self.init_game_sprites()
# 设置定时事件
pygame.time.set_timer(FIRE_EVENT, 800)
pygame.time.set_timer(CREATE_ENEMY_EVENT, 400)
pygame.time.set_timer(SUPER_FIRE_EVENT, 400)
pass
def init_game_sprites(self):
"""
初始化游戏的精灵类
:return:
"""
# 初始化背景精灵加入精灵组
gameBackgroundSprite = GameBackgroundSprite()
gameBackgroundSprite2 = GameBackgroundSprite(isTopBgimage=True)
self.gameBackgroundSpriteGroup = Group(gameBackgroundSprite, gameBackgroundSprite2)
# 初始化玩家飞机添加至精灵组
self.playerPlane = PlayerPlaneSprite()
# self.gameBackgroundSprite2 = PlayerPlaneSprite(PLAYER2_IMAGE_PATH)
self.playerPlaneSpriteGroup = Group(self.playerPlane)
self.enemy_group = Group()
# self.playerPlaneSpriteGroup2 = Group(self.gameBackgroundSprite2)
pass
def start_game(self):
"""开始游戏"""
# 播放背景音乐
self.gameSounds.cycle_play_bgm()
while True:
self.show_score()
self.clock.tick(FRAME_RATE)
# 事件监听
self.event_listener()
# 碰撞检测
self.check_collide()
# 更新精灵图片
self.update_game_sprites()
update_screen()
pass
pass
def update_game_sprites(self):
"""将精灵图组更新显示"""
self.gameBackgroundSpriteGroup.update()
self.gameBackgroundSpriteGroup.draw(self.screen)
self.playerPlaneSpriteGroup.update()
self.playerPlaneSpriteGroup.draw(self.screen)
self.playerPlane.bulletGroup.update()
self.playerPlane.bulletGroup.draw(self.screen)
self.enemy_group.update()
self.enemy_group.draw(self.screen)
update_screen()
pass
def event_listener(self):
"""监听事件"""
for event in pygame.event.get():
# 判断是否退出游戏
if event.type == pygame.QUIT:
exit()
elif event.type == FIRE_EVENT:
if not self.isSuperFire:
self.playerPlane.fire()
# print("自动攻击")
elif event.type == SUPER_FIRE_EVENT:
if self.isSuperFire:
self.playerPlane.super_fire()
self.gameSounds.playerFireSound.play()
self.playerPlane.plane_destroy()
# print("超级火力")
elif event.type == CREATE_ENEMY_EVENT:
enemy = Enemy(enemyMoveSpeed)
# 将敌机精灵添加到敌机精灵组
self.enemy_group.add(enemy)
# print("生成敌机")
moveSpeed = 3
# 捕获键盘事件 按下右键右移,左键反之,上键上移,下键反之
keysPressed = pygame.key.get_pressed()
if keysPressed[pygame.K_RIGHT]:
print("K_RIGHT")
self.playerPlane.moveDirection = "ad"
self.playerPlane.moveSpeed = moveSpeed
pass
elif keysPressed[pygame.K_LEFT]:
print("K_LEFT")
self.playerPlane.moveDirection = "ad"
self.playerPlane.moveSpeed = -moveSpeed
pass
elif keysPressed[pygame.K_UP]:
print("K_UP")
self.playerPlane.moveDirection = "ws"
self.playerPlane.moveSpeed = -moveSpeed
pass
elif keysPressed[pygame.K_DOWN]:
print("K_DOWN")
self.playerPlane.moveDirection = "ws"
self.playerPlane.moveSpeed = moveSpeed
pass
elif keysPressed[pygame.K_SPACE]:
# 按空格切换超级火力
self.isSuperFire = True
# self.playerPlane.isDestroy = True
pass
else:
# print("none_event")
self.playerPlane.moveDirection = " "
self.playerPlane.moveSpeed = 0
self.isSuperFire = False
pass
def check_collide(self):
"""碰撞检测"""
global playerScore
bulletCollideEnemy = pygame.sprite.groupcollide(self.playerPlane.bulletGroup, self.enemy_group, True, True)
if bulletCollideEnemy:
# bulletCollideEnemy.
playerScore += enemyHitedScore
print("子弹撞敌机: 分数=", playerScore)
self.show_score()
# 敌机撞毁英雄
enemyCollidePlayers = pygame.sprite.spritecollide(self.playerPlane, self.enemy_group, True)
if len(enemyCollidePlayers) > 0:
self.playerPlane.isDestroy = True
self.update_game_sprites()
self.clock.tick(3)
self.game_over()
print("敌机撞毁英雄")
pass
def show_score(self):
"""分数显示"""
# global font
scoreFont = self.gameFont.render(f"score: {playerScore}", True, WHITE)
# scoreFont = self.gameFont.render(f"分数: {playerScore}", True, WHITE)
self.screen.blit(scoreFont, (10, 10))
update_screen()
pass
def game_over(self):
"""游戏结束"""
self.gameSounds.playerHitedSound.play()
gameOverImage = load_image_resource(GAMEOVER_IMAGE_PATH)
while True:
self.show_score()
self.show_rank_list()
self.gameSounds.cycle_play_bgm(volume=0)
self.clock.tick(FRAME_RATE)
self.screen.blit(gameOverImage, SCREEN_RECT)
self.event_listener()
def show_rank_list(self):
"""显示排行榜"""
if not self.isFirstAppended:
self.rankList = read_file()
# print(self.rankList)
if playerScore > self.rankList[0]:
self.rankList[0] = playerScore
self.isNewRecord = True
if self.isNewRecord:
self.screen.blit(self.gameFont.render(f"new record: {playerScore}", True, WHITE), (120, 50))
# self.screen.blit(self.gameFont.render(f"新记录: {playerScore}", True, WHITE), (120, 50))
for i in range(len(self.rankList)):
scoreFont = self.gameFont.render(f"{i + 1}: {self.rankList[i]}", True, WHITE)
self.screen.blit(self.gameFont.render("Rank_List", True, WHITE), (180, 250))
# self.screen.blit(self.gameFont.render("排行榜", True, WHITE), (180, 250))
self.screen.blit(scoreFont, (140, 290 + (35 * i)))
if not self.isFirstAppended:
# print("写文件")
self.isFirstAppended = True
self.rankList.append(playerScore)
write_file(self.rankList)
update_screen()
pass
if __name__ == '__main__':
planeGameMain = PlaneGameMain()
planeGameMain.start_game()
pass
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。