forked from matedim/python
/
gamespase.py
266 lines (238 loc) · 8.08 KB
/
gamespase.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# coding: utf8
# Первый полет
# Демонстрация движения астероидов
import random, math
from livewires import games, color
games.init(screen_width = 640, screen_height=480, fps=50)
class Game(object):
"""Игра"""
def __init__(self):
"""Выбор начального уровня"""
#выбор начального игрового уровня
self.level=0
#загрузка звука следующего уровня
self.sound=games.load_sound("level.wav")
#создание обьекта текущего счета
self.score=games.Text(value=0,
size=60,
color=color.white,
top=5,
right=games.screen.width-10,
is_collideable=False)
games.screen.add(self.score)
# создание корабля,которым управляет игрок
self.ship=Ship(game=self,
x=games.screen.width/2,
y=games.screen.height/2)
games.screen.add(self.ship)
def play(self):
"""Старт игры"""
#запуск музыкальной темы
games.music.load("theme.mid")
games.music.play()
#загруска и значение фоновой картинки
nebula_image=games.load_image("nebula.jpg")
games.screen.background=nebula_image
#переход к уровню 1
self.advance()
#начало игры
games.screen.mainloop()
def advance(self):
"""Переводит игру на уровнеь выше"""
self.level+=1
# зарезервированное пространство вокруг корабля
BUFFER=150
#создание новых астероидов
for i in range(self.level):
x_min=random.randrange(BUFFER)
y_min=BUFFER-x_min
x_distance=random.randrange(x_min, games.screen.width-x_min)
y_distance=random.randrange(y_min, games.screen.height-y_min)
x=self.ship.x+x_distance
y=self.ship.y+y_distance
x %=games.screen.width
y %=games.screen.height
new_asteroid = Asteroid(game = self,
x = x, y = y,
size = Asteroid.LARGE)
games.screen.add(new_asteroid)
#отображение номера уровня
level_message=games.Message(value="Level "+str(self.level),
size=40,
color=color.yellow,
x=games.screen.width/2,
y=games.screen.width/10,
lifetime=3*games.screen.fps,
is_collideable=False)
games.screen.add(level_message)
#звуковой эффект перехода (кроме 1 уровня)
if self.level>1:
self.sound.play()
def end(self):
"""Завершение игры"""
#5 секундное завершение игры
end_message=games.Message(value="Game Over",
size=90,
color=color.red,
x=games.screen.width/2,
y=games.screen.height/2,
lifetime=5*games.screen.fps,
after_death=games.screen.quit,
is_collideable=False)
games.screen.add(end_message)
class Wrapper(games.Sprite):
"""Огибатель. Спрайт который двигаясь огибает граф экран"""
def update(self):
"""Переносит спрайт на противоположную сторону"""
if self.top > games.screen.height:
self.bottom = 0
if self.bottom <0:
self.top = games.screen.height
if self.left > games.screen.width:
self.right = 0
if self.right <0:
self.left = games.screen.width
def die(self):
""" Разрушает обьект"""
self.destroy()
class Collider(Wrapper):
"""Погибатель.Огибатель который сталкивается с др обьектами и гибнет"""
def update(self):
"""Проверка спрайтов визуально перекрывающи"""
super(Collider, self).update()
if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die()
self.die()
def die(self):
"""Разрушение обьекта со взрывом"""
new_explosion=Explosion(x=self.x, y=self.y)
games.screen.add(new_explosion)
self.destroy()
class Explosion(games.Animation):
""" Анимированный взрыв"""
sound=games.load_sound("explosion.wav")
images=["explosion1.bmp",
"explosion2.bmp",
"explosion3.bmp",
"explosion4.bmp",
"explosion5.bmp",
"explosion6.bmp",
"explosion7.bmp",
"explosion8.bmp",
"explosion9.bmp"]
def __init__(self, x, y):
super(Explosion, self).__init__(images=Explosion.images,
x=x, y=y,
repeat_interval=4,
n_repeats=1,
is_collideable = False)
Explosion.sound.play()
class Asteroid(Wrapper):
""" An asteroid which floats across the screen. """
SMALL = 1
MEDIUM = 2
LARGE = 3
images = {SMALL : games.load_image("asteroid_small.bmp"),
MEDIUM : games.load_image("asteroid_med.bmp"),
LARGE : games.load_image("asteroid_big.bmp") }
SPAWN = 2
SPEED = 2
POINTS=30
total=0
def __init__(self, game,x, y, size):
""" Initialize asteroid sprite. """
Asteroid.total+=1
super(Asteroid, self).__init__(
image = Asteroid.images[size],
x = x, y = y,
dx = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size,
dy = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size)
self.size = size
self.game=game
def die(self):
""" Разрушает астероид"""
Asteroid.total-=1
self.game.score.value+=int(Asteroid.POINTS/self.size)
self.game.score.right=games.screen.width-10
if self.size != Asteroid.SMALL:
for i in range(Asteroid.SPAWN):
new_asteriod = Asteroid(game=self.game,
x=self.x,
y=self.y,
size=self.size-1)
games.screen.add(new_asteriod)
if Asteroid.total ==0:
self.game.advance()
super(Asteroid, self).die()
class Ship(Collider):
"""docstring for Ship"""
image=games.load_image("ship.bmp")
ROTETION_STEP=3
VELOCITY_STEP = .03
VELOCITY_MAX=3
MISSILE_DELAY=25
sound=games.load_sound("thrust.wav")
def __init__(self, game, x, y):
""" Initialize ship sprite. """
super(Ship, self).__init__(image = Ship.image, x = x, y = y)
self.missile_wait = 0
self.game=game
def update(self):
"""Вращение корабля при нажатии клавишь"""
super(Ship, self).update()
if games.keyboard.is_pressed(games.K_LEFT):
self.angle-=Ship.ROTETION_STEP
if games.keyboard.is_pressed(games.K_RIGHT):
self.angle+=Ship.ROTETION_STEP
#корабль совершает рывок
if games.keyboard.is_pressed(games.K_UP):
Ship.sound.play()
#изменение гориз и верт скорости корабля
angle=self.angle*math.pi/180
self.dx += Ship.VELOCITY_STEP * math.sin(angle)
self.dy += Ship.VELOCITY_STEP * -math.cos(angle)
self.dx=min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
self.dy=min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
# if waiting until the ship can fire next, decrease wait
if self.missile_wait > 0:
self.missile_wait -= 1
# Стрельба
if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait ==0:
new_missile=Missile(self.x, self.y, self.angle)
games.screen.add(new_missile)
self.missile_wait=Ship.MISSILE_DELAY
def die(self):
self.game.end()
super(Ship,self).die()
class Missile(Collider):
"""Ракеты коробля"""
image=games.load_image("missile.bmp")
sound=games.load_sound("missile.wav")
BUFFER=40
VELOCITY_FACTOR=7
LIFETIME=40
def __init__(self, ship_x, ship_y, ship_angle):
"""Инициализация ракеты"""
Missile.sound.play()
angle=ship_angle*math.pi/180
buffer_x=Missile.BUFFER*math.sin(angle)
buffer_y=Missile.BUFFER*-math.cos(angle)
x=ship_x+buffer_x
y=ship_y+buffer_y
dx=Missile.VELOCITY_FACTOR*math.sin(angle)
dy=Missile.VELOCITY_FACTOR*-math.cos(angle)
super(Missile, self).__init__(image=Missile.image,
x=x, y=y,
dx=dx, dy=dy)
self.lifetime=Missile.LIFETIME
def update(self):
""" Перемещает ракету"""
super(Missile, self).update()
self.lifetime-=1
if self.lifetime ==0:
self.destroy()
def main():
astocrash=Game()
astocrash.play()
main()