-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsprite.py
More file actions
145 lines (97 loc) · 3.48 KB
/
sprite.py
File metadata and controls
145 lines (97 loc) · 3.48 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import random
import pygame
# 屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
# 刷新的帧率
FPS = 60
# 创建敌机的定时器常量
CREATE_ENEMY_EVENT = pygame.USEREVENT
# 英雄发射子弹事件
HERO_FIRE_EVENT = pygame.USEREVENT + 1
class GameSprite(pygame.sprite.Sprite):
"""游戏精灵"""
def __init__(self, image_name, speed=1):
# 调用父类的初始化方法
super().__init__()
# 定义对象的属性
self.image = pygame.image.load(image_name)
self.rect = self.image.get_rect()
self.speed = speed
# 重写父类update()方法
def update(self):
# 在屏幕垂直方向上移动
self.rect.y += self.speed
class BackGround(GameSprite):
"""游戏背景精灵"""
def __init__(self, is_alt=False):
# 调用父类方法实现精灵创建
super().__init__("images/background.png")
# 判断是否是交替图像, 如果是, 需要设置初始位置
if is_alt:
self.rect.y = -self.rect.height
def update(self):
# 调用父类的update方法
super().update()
# 判断是否移出屏幕
if self.rect.y >= SCREEN_RECT.height:
self.rect.y = -self.rect.height
class Enemy(GameSprite):
"""敌机精灵"""
def __init__(self):
# 调用父类方法,创建敌机精灵,同时指定敌机图片
super().__init__("images\enemy1.png")
# 指定敌机的初始随机速度
self.speed = random.randint(1, 3)
# 指定敌机的初始随机位置
self.rect.bottom = 0
max_x = SCREEN_RECT.width - self.rect.width
self.rect.x = random.randint(0, max_x)
def update(self):
# 调用父类方法, 保持垂直方向飞行
super().update()
# 判断是否非处屏幕, 如果是, 需要从精灵组删除敌机
if self.rect.y >= SCREEN_RECT.height:
print("飞出屏幕,删除...")
self.kill()
def __del__(self):
print("敌机挂了 %s" % self.rect)
class Hero(GameSprite):
"""英雄精灵"""
def __init__(self):
# 调用父类方法,创建英雄精灵,同时指定敌机图片和速度
super().__init__("images/me1.png", 0)
# 设置英雄的初始位置
self.rect.centerx = SCREEN_RECT.centerx
self.rect.bottom = SCREEN_RECT.bottom - 120
# 创建子弹精灵组
self.bullets = pygame.sprite.Group()
def update(self):
# 英雄在水平方向移动
self.rect.x += self.speed
# 控制英雄不能离开屏幕
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.right > SCREEN_RECT.right:
self.rect.right = SCREEN_RECT.right
def fire(self):
print("发射子弹...")
for i in (0, 1, 2):
# 创建子弹精灵
bullet = Bullet()
# 设置精灵位置
bullet.rect.bottom = self.rect.y - i * 20
bullet.rect.centerx = self.rect.centerx
# 将子弹精灵添加到子弹精灵组
self.bullets.add(bullet)
class Bullet(GameSprite):
"""子弹精灵"""
def __init__(self):
super().__init__("images/bullet1.png", -2)
def update(self):
# 调用父类方法, 让子弹垂直移动
super().update()
# 判断子弹是否飞出屏幕
if self.rect.bottom < 0:
self.kill()
def __del__(self):
print("子弹被销毁")