-
Notifications
You must be signed in to change notification settings - Fork 0
/
plane_main.py
119 lines (95 loc) · 3.67 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
110
111
112
113
114
115
116
117
118
119
from plane_sprites import *
class PlaneGame:
'''飞机大战主游戏'''
def __init__(self):
print('游戏初始化')
#1.创建游戏的窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.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, 500) #英雄每隔0.5s发射子弹
def __create_sprites(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 1:
#1设置刷新帧率
self.clock.tick(FRAME_PER_SEC)
#2事件监听
self.__event_handler()
#3碰撞检测
self.__check_collide()
#4更新/绘制精灵组
self.__update_sprites()
#更新显示
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 = Enemy()
#将敌机精灵添加到敌机精灵组
self.enemy_group.add(enemy)
elif event.type == HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type == pygame.KEYDOWN and event.key in (pygame.K_RIGHT,pygame.K_d):
# print('向右移动……')
#使用键盘提供的方法获取键盘按键,返回按键元祖
keys_pressed = pygame.key.get_pressed()
#判断元祖中对应的按键索引值 1
if keys_pressed[pygame.K_RIGHT]:
self.hero.speed = 2
elif keys_pressed[pygame.K_d]:
self.hero.speed = 2
elif keys_pressed[pygame.K_LEFT]:
self.hero.speed = -2
elif keys_pressed[pygame.K_a]:
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敌机撞毁英雄
enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
#3判断列表是否有内容
if len(enemies) > 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__':
#创建游戏对象
game = PlaneGame()
#启动游戏
game.start_game()