-
Notifications
You must be signed in to change notification settings - Fork 0
/
plane_main.py
81 lines (71 loc) · 2.49 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
import pygame
from plane_sprites import *
class PlaneGame(object):
"""飞机大战主游戏"""
def __init__(self):
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
self.clock = pygame.time.Clock()
self.__create_sprites()
pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
pygame.time.set_timer(HERO_FIRE_EVENT, 500)
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):
"""开始游戏"""
while True:
self.clock.tick(FRAME_PER_SEC)
self.__event_handler()
self.__check_collide()
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:
enemy = Enemy()
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 = 3
elif keys_pressed[pygame.K_LEFT]:
self.hero.speed = -3
else:
self.hero.speed = 0
def __check_collide(self):
"""检查碰撞"""
# 子弹摧毁敌机
pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
# 敌机撞毁英雄飞机
enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
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__":
one = PlaneGame()
one.start_game()