Commit a30ce040 authored by 13680905's avatar 13680905
Browse files

Upload New File

parent 922654d7
import pygame
from planes_sprites import *
pygame.init()
myfont = pygame.font.Font(None, 60)
white = (255, 255, 255)
blue = (0, 0, 255)
num=0
class PlaneGame(object):
'''飞机大战主游戏'''
def __init__(self):
print("游戏初始化")
#1.创建游戏窗口
self.screen =pygame.display.set_mode(SCREEN_RECT.size)#size属性为元组
#2.创建游戏时钟
self.clock =pygame.time.Clock()
#3.调用私有方法,创建精灵,精灵组
self.__create_sprites()
#4,设置定时器事件 - 创建敌机 1s
pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)
pygame.time.set_timer(HERO_FIRE_EVENT,100)
self.enemy=None
#创建精灵
def __create_sprites(self):
#创建背景精灵和精灵组
bg1=Background()
bg2=Background(True)
self.back_group=pygame.sprite.Group(bg1,bg2)
#创建敌机精灵组
self.enemy_group=pygame.sprite.Group()
#创建英雄精灵和精灵组
self.hero = Hero()
self.hero_group=pygame.sprite.Group(self.hero)
def start_game(self):
print("游戏开始")
while True:
#1,设置刷新帧率
self.clock.tick(FRAME_PER_SEC)
#2.事件监听
self.__event_handler()
#3.碰撞检测
self.__check_collide()
#4.更新/绘制精灵组
self.__update_sprites()
#5.更新显示
pygame.display.update()
def __event_handler(self):
for event in pygame.event.get():
#判断是否退出游戏
if event.type==pygame.QUIT:
PlaneGame.__game_over()
elif event.type==CREATE_ENEMY_EVENT:
'''print("敌机出场")'''
#创建敌机精灵
self.enemy=Enemy()
#将敌机精灵增加到敌机精灵组
self.enemy_group.add(self.enemy)
elif event.type == HERO_FIRE_EVENT:
# 创建子弹
self.bullet = Bullet
self.hero.fire()
'''elif event.type==pygame.KEYDOWN and event.key==pygame.K_RIGHT:
print("右键测试")
self.hero.speed =1'''
#使用键盘提供的方法获取键盘按键
keys_pressed=pygame.key.get_pressed()
#判断元组中对应的案件索引值
if keys_pressed[pygame.K_RIGHT]:
'''print("向右移动")'''
self.hero.speed = 2
elif keys_pressed[pygame.K_LEFT]:
'''print("向左移动")'''
self.hero.speed = -2
else:
self.hero.speed=0
def __check_collide(self):
#在所有敌机中遍历循环
for enemy in self.enemy_group:
#判断敌机是否生成
if enemy is not None:
#英雄飞机和敌机的碰撞检测
#判断敌机是否处于碰撞x理想值
if self.hero.rect.x<=enemy.rect.x +53 and self.hero.rect.x+102>=enemy.rect.x :
#判断敌机是否处于碰撞y理想值
pass
if self.hero.rect.y<=enemy.rect.y+43:
'''print("撞上了")'''
global num
num+= 1
enemy.kill()
def __update_sprites(self):
pygame.display.update()
self.back_group.update()
self.back_group.draw(self.screen)
self.enemy_group.update()
self.enemy_group.draw(self.screen)
self.hero_group.update()
self.hero_group.draw(self.screen)
j=("score:'%d'"%num)
textImage = myfont.render(j, True, white)
self.screen.blit(textImage, (0, 0))
self.hero.bulltes.update()
self.hero.bulltes.draw(self.screen)
@staticmethod
def __game_over():
print("游戏结束")
pygame.quit()
exit()
if __name__ == '__main__':#表示能够在主程序直接运行
#创建游戏对象
game = PlaneGame()
game.start_game()
#启动游戏
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment