-
Notifications
You must be signed in to change notification settings - Fork 2
/
asteroids.py
408 lines (337 loc) · 12.9 KB
/
asteroids.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# Notes:
# random.randrange returns an int
# random.uniform returns a float
# p for pause
# j for toggle showing FPS
# o for frame advance whilst paused
import pygame
import sys
import os
import random
from pygame.locals import *
from util.vectorsprites import *
from ship import *
from stage import *
from badies import *
from shooter import *
from soundManager import *
class Asteroids():
explodingTtl = 180
def __init__(self):
self.stage = Stage('Asteroids', (1024, 768))
self.paused = False
self.showingFPS = False
self.frameAdvance = False
self.gameState = "attract_mode"
self.rockList = []
self.createRocks(3)
self.saucer = None
self.secondsCount = 1
self.score = 0
self.ship = None
self.lives = 0
def initialiseGame(self):
self.gameState = 'playing'
[self.stage.removeSprite(sprite)
for sprite in self.rockList] # clear old rocks
if self.saucer is not None:
self.killSaucer()
self.startLives = 5
self.createNewShip()
self.createLivesList()
self.score = 0
self.rockList = []
self.numRocks = 3
self.nextLife = 10000
self.createRocks(self.numRocks)
self.secondsCount = 1
def createNewShip(self):
if self.ship:
[self.stage.spriteList.remove(debris)
for debris in self.ship.shipDebrisList]
self.ship = Ship(self.stage)
self.stage.addSprite(self.ship.thrustJet)
self.stage.addSprite(self.ship)
def createLivesList(self):
self.lives += 1
self.livesList = []
for i in range(1, self.startLives):
self.addLife(i)
def addLife(self, lifeNumber):
self.lives += 1
ship = Ship(self.stage)
self.stage.addSprite(ship)
ship.position.x = self.stage.width - \
(lifeNumber * ship.boundingRect.width) - 10
ship.position.y = 0 + ship.boundingRect.height
self.livesList.append(ship)
def createRocks(self, numRocks):
for _ in range(0, numRocks):
position = Vector2d(random.randrange(-10, 10),
random.randrange(-10, 10))
newRock = Rock(self.stage, position, Rock.largeRockType)
self.stage.addSprite(newRock)
self.rockList.append(newRock)
def playGame(self):
clock = pygame.time.Clock()
frameCount = 0.0
timePassed = 0.0
self.fps = 0.0
# Main loop
while True:
# calculate fps
timePassed += clock.tick(60)
frameCount += 1
if frameCount % 10 == 0: # every 10 frames
# nearest integer
self.fps = round((frameCount / (timePassed / 1000.0)))
# reset counter
timePassed = 0
frameCount = 0
self.secondsCount += 1
self.input(pygame.event.get())
# pause
if self.paused and not self.frameAdvance:
self.displayPaused()
continue
self.stage.screen.fill((10, 10, 10))
self.stage.moveSprites()
self.stage.drawSprites()
self.doSaucerLogic()
self.displayScore()
if self.showingFPS:
self.displayFps() # for debug
self.checkScore()
# Process keys
if self.gameState == 'playing':
self.playing()
elif self.gameState == 'exploding':
self.exploding()
else:
self.displayText()
# Double buffer draw
pygame.display.flip()
def playing(self):
if self.lives == 0:
self.gameState = 'attract_mode'
else:
self.processKeys()
self.checkCollisions()
if len(self.rockList) == 0:
self.levelUp()
def doSaucerLogic(self):
if self.saucer is not None:
if self.saucer.laps >= 2:
self.killSaucer()
# Create a saucer
if self.secondsCount % 2000 == 0 and self.saucer is None:
randVal = random.randrange(0, 10)
if randVal <= 3:
self.saucer = Saucer(
self.stage, Saucer.smallSaucerType, self.ship)
else:
self.saucer = Saucer(
self.stage, Saucer.largeSaucerType, self.ship)
self.stage.addSprite(self.saucer)
def exploding(self):
self.explodingCount += 1
if self.explodingCount > self.explodingTtl:
self.gameState = 'playing'
[self.stage.spriteList.remove(debris)
for debris in self.ship.shipDebrisList]
self.ship.shipDebrisList = []
if self.lives == 0:
self.ship.visible = False
else:
self.createNewShip()
def levelUp(self):
self.numRocks += 1
self.createRocks(self.numRocks)
# move this kack somewhere else!
def displayText(self):
font1 = pygame.font.Font('../res/Hyperspace.otf', 50)
font2 = pygame.font.Font('../res/Hyperspace.otf', 20)
font3 = pygame.font.Font('../res/Hyperspace.otf', 30)
titleText = font1.render('Asteroids', True, (180, 180, 180))
titleTextRect = titleText.get_rect(centerx=self.stage.width/2)
titleTextRect.y = self.stage.height/2 - titleTextRect.height*2
self.stage.screen.blit(titleText, titleTextRect)
keysText = font2.render(
'(C) 1979 - 2021 Boularbah Ismail.', True, (255, 255, 255))
keysTextRect = keysText.get_rect(centerx=self.stage.width/2)
keysTextRect.y = self.stage.height - keysTextRect.height - 20
self.stage.screen.blit(keysText, keysTextRect)
instructionText = font3.render(
'Press enter to start', True, (200, 200, 200))
instructionTextRect = instructionText.get_rect(
centerx=self.stage.width/2)
instructionTextRect.y = self.stage.height/2 - instructionTextRect.height
self.stage.screen.blit(instructionText, instructionTextRect)
def displayScore(self):
font1 = pygame.font.Font('../res/Hyperspace.otf', 30)
font2 = pygame.font.Font('../res/Hyperspace.otf', 25)
scoreStr = str("%02d" % self.score)
scoreText = font2.render('Score:' + scoreStr, True, (200, 200, 200))
scoreTextRect = scoreText.get_rect(centerx=100, centery=45)
self.stage.screen.blit(scoreText, scoreTextRect)
def displayPaused(self):
if self.paused:
font1 = pygame.font.Font('../res/Hyperspace.otf', 30)
pausedText = font1.render("Paused", True, (255, 255, 255))
textRect = pausedText.get_rect(
centerx=self.stage.width/2, centery=self.stage.height/2)
self.stage.screen.blit(pausedText, textRect)
pygame.display.update()
# Should move the ship controls into the ship class
def input(self, events):
self.frameAdvance = False
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit(0)
if self.gameState == 'playing':
if event.key == K_SPACE:
self.ship.fireBullet()
elif event.key == K_b:
self.ship.fireBullet()
elif event.key == K_h:
self.ship.enterHyperSpace()
elif self.gameState == 'attract_mode':
# Start a new game
if event.key == K_RETURN:
self.initialiseGame()
if event.key == K_p:
if self.paused: # (is True)
self.paused = False
else:
self.paused = True
if event.key == K_j:
if self.showingFPS: # (is True)
self.showingFPS = False
else:
self.showingFPS = True
if event.key == K_f:
pygame.display.toggle_fullscreen()
# if event.key == K_k:
# self.killShip()
elif event.type == KEYUP:
if event.key == K_o:
self.frameAdvance = True
def processKeys(self):
key = pygame.key.get_pressed()
if key[K_LEFT] or key[K_z]:
self.ship.rotateLeft()
elif key[K_RIGHT] or key[K_x]:
self.ship.rotateRight()
if key[K_UP] or key[K_n]:
self.ship.increaseThrust()
self.ship.thrustJet.accelerating = True
else:
self.ship.thrustJet.accelerating = False
# Check for ship hitting the rocks etc.
def checkCollisions(self):
# Ship bullet hit rock?
newRocks = []
shipHit, saucerHit = False, False
# Rocks
for rock in self.rockList:
rockHit = False
if not self.ship.inHyperSpace and rock.collidesWith(self.ship):
p = rock.checkPolygonCollision(self.ship)
if p is not None:
shipHit = True
rockHit = True
if self.saucer is not None:
if rock.collidesWith(self.saucer):
saucerHit = True
rockHit = True
if self.saucer.bulletCollision(rock):
rockHit = True
if self.ship.bulletCollision(self.saucer):
saucerHit = True
self.score += self.saucer.scoreValue
if self.ship.bulletCollision(rock):
rockHit = True
if rockHit:
self.rockList.remove(rock)
self.stage.spriteList.remove(rock)
if rock.rockType == Rock.largeRockType:
playSound("explode1")
newRockType = Rock.mediumRockType
self.score += 50
elif rock.rockType == Rock.mediumRockType:
playSound("explode2")
newRockType = Rock.smallRockType
self.score += 100
else:
playSound("explode3")
self.score += 200
if rock.rockType != Rock.smallRockType:
# new rocks
for _ in range(0, 2):
position = Vector2d(rock.position.x, rock.position.y)
newRock = Rock(self.stage, position, newRockType)
self.stage.addSprite(newRock)
self.rockList.append(newRock)
self.createDebris(rock)
# Saucer bullets
if self.saucer is not None:
if not self.ship.inHyperSpace:
if self.saucer.bulletCollision(self.ship):
shipHit = True
if self.saucer.collidesWith(self.ship):
shipHit = True
saucerHit = True
if saucerHit:
self.createDebris(self.saucer)
self.killSaucer()
if shipHit:
self.killShip()
# comment in to pause on collision
#self.paused = True
def killShip(self):
stopSound("thrust")
playSound("explode2")
self.explodingCount = 0
self.lives -= 1
if (self.livesList):
ship = self.livesList.pop()
self.stage.removeSprite(ship)
self.stage.removeSprite(self.ship)
self.stage.removeSprite(self.ship.thrustJet)
self.gameState = 'exploding'
self.ship.explode()
def killSaucer(self):
stopSound("lsaucer")
stopSound("ssaucer")
playSound("explode2")
self.stage.removeSprite(self.saucer)
self.saucer = None
def createDebris(self, sprite):
for _ in range(0, 25):
position = Vector2d(sprite.position.x, sprite.position.y)
debris = Debris(position, self.stage)
self.stage.addSprite(debris)
def displayFps(self):
font2 = pygame.font.Font('../res/Hyperspace.otf', 15)
fpsStr = str(self.fps)+(' FPS')
scoreText = font2.render(fpsStr, True, (255, 255, 255))
scoreTextRect = scoreText.get_rect(
centerx=(self.stage.width/2), centery=15)
self.stage.screen.blit(scoreText, scoreTextRect)
def checkScore(self):
if self.score > 0 and self.score > self.nextLife:
playSound("extralife")
self.nextLife += 10000
self.addLife(self.lives)
# Script to run the game
if not pygame.font:
print('Warning, fonts disabled')
if not pygame.mixer:
print('Warning, sound disabled')
initSoundManager()
game = Asteroids() # create object game from class Asteroids
game.playGame()
####