-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAlienAttack.py
More file actions
439 lines (366 loc) · 12.6 KB
/
AlienAttack.py
File metadata and controls
439 lines (366 loc) · 12.6 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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# Fun Game by Vichitr
# Developed in Python using pygame
# import the modules
import pygame,random,sys
from pygame.locals import *
# set the window size
WINDOWWIDTH = 900
WINDOWHEIGHT = 700
# set the colors
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
GREEN = (0, 128,0)
# set the constant variables
FPS = 30
ALIENMINSPEED = 1
ALIENMAXSPEED = 4
ADDNEWALIENRATE = 10
ADDNEWALIEN1RATE = 20
ADDSUPERALIENRATE = 40
PLAYERMOVERATE = 5
ALIENSIZE = 50
BULLETSPEED = 4
NOSUPERBULLETS = 5
POWERUPRATE = 1000
POWERUPSIZE = 50
POWERUPSPEED = 4
ADDNEWLIFERATE = 3000
LIFESIZE = 50
PAUSE = False
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
# define a function to draw text on the screen
def drawText(text,font,surface, x, y):
textobj= font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Alien Attack')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None,48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage1 = pygame.image.load('spaceship.png')
playerImage = pygame.transform.scale(playerImage1, (60,60))
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('alien.png')
alien1Image = pygame.image.load('alien1.png')
superAlienImage = pygame.image.load('superalien.png')
lifeImage = pygame.image.load('life.png')
powerUpImage = pygame.image.load('powerup.png')
superBulletImage = pygame.image.load('superbullet.png')
# set up the background
background = pygame.image.load("background.png")
backgroundImage = pygame.transform.scale(background,(WINDOWWIDTH,WINDOWHEIGHT))
backgroundRect = backgroundImage.get_rect()
# show the start screen
drawText('Alien Attack',font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start!', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
highScore = 0
while True:
# set up the start of the game
aliens=[]
aliens1=[]
superAliens = []
spaceshipBullets = []
superBullets = []
alienBullets = []
superPower = []
lifes = []
score = 0
levelUpScore = 1000
level = 0
LIFES = 3
playerRect.topleft = (WINDOWWIDTH/2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
alienAddCounter = 0
alien1AddCounter = 0
superAlienAddCounter = 0
superPowerCounter = 0
newLifeCounter = 0
pygame.mixer.music.play(-1,0.0)
# update the background of the window
windowSurface.blit(backgroundImage, backgroundRect)
pygame.display.update()
while True: # the game loop runs while the game part is playing
# pause the game
while PAUSE == True: # wait till the player resumes the game
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('p'):
PAUSE = False
# quit the game
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == K_SPACE:
# create new bullets if space is pressed
newSpaceshipBullet1 = pygame.Rect(playerRect.centerx-20, playerRect.centery+5, 3, 6)
spaceshipBullets.append(newSpaceshipBullet1)
newSpaceshipBullet2 = pygame.Rect(playerRect.centerx+15, playerRect.centery+5, 3, 6)
spaceshipBullets.append(newSpaceshipBullet2)
if event.key == K_LALT and NOSUPERBULLETS > 0:
# use the super bullets when left alt is pressed
newSuperBullet = {'rect': pygame.Rect(playerRect.centerx-12, playerRect.centery-50, 20, 50), 'surface': pygame.transform.scale(superBulletImage, (20,50))}
superBullets.append(newSuperBullet)
NOSUPERBULLETS -= 1
if event.type == KEYUP:
if event.key == K_ESCAPE: # exit the game
terminate()
if event.key == ord('p'): # pause the game
PAUSE = True
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
# move spaceship as mouse moves
if event.type == MOUSEMOTION:
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# add aliens at the top of the screen
alienAddCounter += 1
if alienAddCounter == ADDNEWALIENRATE:
alienAddCounter = 0
newAlien = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH - ALIENSIZE),0 - ALIENSIZE, ALIENSIZE, ALIENSIZE), 'speed': random.randint(ALIENMINSPEED,ALIENMAXSPEED),'surface': pygame.transform.scale(alienImage, (ALIENSIZE, ALIENSIZE))}
aliens.append(newAlien)
# add different type aliens
alien1AddCounter += 1
if alien1AddCounter == ADDNEWALIEN1RATE:
alien1AddCounter = 0
newAlien1 = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH - ALIENSIZE), 0 - ALIENSIZE, ALIENSIZE, ALIENSIZE), 'speed': random.randint(ALIENMINSPEED, ALIENMAXSPEED), 'surface': pygame.transform.scale(alien1Image,(ALIENSIZE, ALIENSIZE))}
aliens1.append(newAlien1)
# add super aliens
superAlienAddCounter += 1
if superAlienAddCounter == ADDSUPERALIENRATE:
superAlienAddCounter = 0
newSuperAlien = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH - ALIENSIZE), 0 - ALIENSIZE, ALIENSIZE, ALIENSIZE), 'speed': random.randint(ALIENMINSPEED, ALIENMAXSPEED), 'surface': pygame.transform.scale(superAlienImage, (ALIENSIZE, ALIENSIZE)), 'hit': 3}
superAliens.append(newSuperAlien)
# add powerups to increase no of super bullets
superPowerCounter += 1
if superPowerCounter == POWERUPRATE:
superPowerCounter = 0
newPower = {'rect': pygame.Rect(random.randint(0,WINDOWWIDTH - POWERUPSIZE), 0 - POWERUPSIZE, POWERUPSIZE, POWERUPSIZE), 'surface': pygame.transform.scale(powerUpImage, (POWERUPSIZE, POWERUPSIZE))}
superPower.append(newPower)
# add new powerup to increase the no of lifes
newLifeCounter += 1
if newLifeCounter == ADDNEWLIFERATE:
newLifeCounter = 0
newLife = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH - LIFESIZE), 0 - LIFESIZE, LIFESIZE, LIFESIZE), 'surface': pygame.transform.scale(lifeImage, (LIFESIZE, LIFESIZE))}
lifes.append(newLife)
# move the spaceship around
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# move the mouse cursor to match the player
pygame.mouse.set_pos(playerRect.centerx,playerRect.centery)
# move the aliens down
for a in aliens:
a['rect'].move_ip(0,a['speed'])
for a1 in aliens1:
a1['rect'].move_ip(0, a1['speed'])
for sa in superAliens:
sa['rect'].move_ip(0, sa['speed'])
# move the powerups down
for p in superPower[:]:
p['rect'].move_ip(0, POWERUPSPEED)
for l in lifes[:]:
l['rect'].move_ip(0, POWERUPSPEED)
# move the bullets up
for b in spaceshipBullets:
b.move_ip(0,-BULLETSPEED)
for s in superBullets:
s['rect'].move_ip(0,-BULLETSPEED)
# delete bullets that have moved past the top
for b in spaceshipBullets[:]:
if b.top < 0:
spaceshipBullets.remove(b)
for s in superBullets[:]:
if s['rect'].top <0:
superBullets.remove(s)
# delete aliens that have fallen past the bottom
for a in aliens[:]:
if a['rect'].top > WINDOWHEIGHT:
aliens.remove(a)
for a1 in aliens1[:]:
if a1['rect'].top > WINDOWHEIGHT:
aliens1.remove(a1)
for sa in superAliens[:]:
if sa['rect'].top > WINDOWHEIGHT:
superAliens.remove(sa)
# delete powerups that have fallen past the bottom
for l in lifes[:]:
if l['rect'].top > WINDOWHEIGHT:
lifes.remove(l)
for p in superPower[:]:
if p['rect'].top > WINDOWHEIGHT:
superPower.remove(p)
# draw the game world on the window
windowSurface.blit(backgroundImage, backgroundRect)
pygame.display.update()
#windowSurface.fill(BACKGROUNDCOLOR)
# draw the score, high score, Lifes and super bullets
drawText('Score: %s' %(score), font, windowSurface, 10, 0)
drawText('High Score: %s' %(highScore),font, windowSurface, 10,30)
drawText('Super Bullets: %s' %(NOSUPERBULLETS),font, windowSurface, WINDOWWIDTH - 260, 30)
drawText('Lifes: %s' %(LIFES), font, windowSurface, WINDOWWIDTH - 260, 0)
# draw the spaceship
windowSurface.blit(playerImage, playerRect)
pygame.display.update()
# draw the aliens
for a in aliens:
windowSurface.blit(a['surface'], a['rect'])
for a1 in aliens1:
windowSurface.blit(a1['surface'],a1['rect'])
for sa in superAliens:
windowSurface.blit(sa['surface'],sa['rect'])
# draw the powerups
for l in lifes:
windowSurface.blit(l['surface'],l['rect'])
# draw the bullets
for b in spaceshipBullets:
pygame.draw.rect(windowSurface, BLUE, b, 0)
for s in superBullets:
windowSurface.blit(s['surface'], s['rect'])
# draw the powerups
for p in superPower:
windowSurface.blit(p['surface'], p['rect'])
# check if bullets have hit the aliens
for b in spaceshipBullets:
for a in aliens:
if b.colliderect(a['rect']):
score += 10 # increase the score
aliens.remove(a)
spaceshipBullets.remove(b)
break
for b in spaceshipBullets:
for a1 in aliens1:
if b.colliderect(a1['rect']):
score += 15 # increase the score
aliens1.remove(a1)
spaceshipBullets.remove(b)
break
for b in spaceshipBullets:
for sa in superAliens:
if b.colliderect(sa['rect']):
sa['hit'] -= 1
# check bullets have hit the super aliens 3 times
if sa['hit'] > 0:
spaceshipBullets.remove(b)
break
else:
score += 30 # increase the score
superAliens.remove(sa)
spaceshipBullets.remove(b)
break
# if super bullets hit the aliens, increase more score
for s in superBullets:
for a in aliens:
if s['rect'].colliderect(a['rect']):
score += 20
aliens.remove(a)
for s in superBullets:
for a1 in aliens1:
if s['rect'].colliderect(a1['rect']):
score += 30
aliens1.remove(a1)
for s in superBullets:
for sa in superAliens:
if s['rect'].colliderect(sa['rect']):
score += 60
superAliens.remove(sa)
# if powerup is catched by spaceship
for p in superPower:
if playerRect.colliderect(p['rect']):
if NOSUPERBULLETS < 9:
NOSUPERBULLETS += 1
superPower.remove(p)
for l in lifes:
if playerRect.colliderect(l['rect']):
if LIFES < 3:
LIFES += 1
lifes.remove(l)
# increase the difficulty if game proceeds
if score >= levelUpScore:
levelUpScore += 1000
level += 1
ALIENMINSPEED += 1
ALIENMAXSPEED += 1
# update the window
pygame.display.update()
# if aliens hit the spaceship decrease lifes
for a in aliens:
if playerRect.colliderect(a['rect']):
aliens.remove(a)
LIFES -= 1
for a1 in aliens1:
if playerRect.colliderect(a1['rect']):
aliens1.remove(a1)
LIFES -= 1
for sa in superAliens:
if playerRect.colliderect(sa['rect']):
LIFES -= 1
superAliens.remove(sa)
# if lifes are zero, end the game
if LIFES <= 0:
if score > highScore:
# set up high score
highScore= score
NOSUPERBULLETS = 5
break
mainClock.tick(FPS)
# set the speed to the initial ones
ALIENMINSPEED = 1
ALIENMAXSPEED = 4
# stop the game sound and play game over sound
pygame.mixer.music.stop()
gameOverSound.play()
# show the 'Game Over' screen
drawText('GAME OVER',font,windowSurface, (WINDOWWIDTH / 3),(WINDOWHEIGHT / 3))
drawText('Press a key to play again.',font,windowSurface, (WINDOWWIDTH / 3) -80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
# stop the game over sound
gameOverSound.stop()