-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplane_main.py
109 lines (85 loc) · 3.09 KB
/
plane_main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import pygame
from 飞机精灵 import *
class PlaneGame(object):
"""飞机大战主游戏"""
def __init__(self):
print("游戏初始化")
#1,创建游戏的窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
#2,创建游戏的时钟
self.clock = pygame.time.Clock()
#3调用私有方法,精灵和精灵组1创建
self.__create_sprities()
# 4,设置定时器事件 - 创建敌机 1s
pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
pygame.time.set_timer(HERO_FIRE_EVENT,500)
def __create_sprities(self):
# 创建精灵和精灵组
bg1 = BackGround()
bg2 = BackGround(is_alt=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(FRAM_OER_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("敌机出场...")
#创建敌机精灵
enemy = Enmy()
#将敌机精灵添加到敌机精灵组
self.enemy_group.add(enemy)
elif event.type == HERO_FIRE_EVENT:
self.hero.fire()
#使用键盘提供的方法获得键盘按键
keys_pressed = pygame.key.get_pressed()
#判断元祖中对应的索引值
if keys_pressed[pygame.K_RIGHT]:
self.hero.speed = 2
elif keys_pressed[pygame.K_LEFT]:
self.hero.speed = -2
else:
self.hero.speed = 0
def __check_collide(self):
#1,子弹摧毁敌机
pygame.sprite.groupcollide(self.hero.bullets , self.enemy_group, True , True)
#2,敌机撞毁英雄
enemines = pygame.sprite.spritecollide(self.hero, self.enemy_group ,True)
#判断列表是否有内容
if len(enemines) > 0 :
#让英雄牺牲
self.hero.kill()
# 结束游戏
PlaneGame.__game_over()
def __update_sprites(self):
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)
self.hero.bullets.update()
self.hero.bullets.draw(self.screen)
@staticmethod
def __game_over():
print("游戏结束")
pygame.quit()
exit()
if __name__ == '__main__':
PlaneGame().start_game()