-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
525 lines (408 loc) · 17.2 KB
/
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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import pygame
from sys import exit
import math
import random
from game import Game
from player import Player
from projectile import Projectile
from enemy import Enemy
from gameObject import GameObject
from spark import Spark
from flame import Flame
# Initialize pygame subsystems
pygame.init()
pygame.mixer.init()
# Game state object
game = Game()
# Groups
# Player group
player = pygame.sprite.GroupSingle()
# Projectile group
projectileGroup = pygame.sprite.Group()
# Enemy group
enemyGroup = pygame.sprite.Group()
# Object group
objectGroup = pygame.sprite.Group()
# Flame group
flameGroup = pygame.sprite.GroupSingle()
# Spark group
sparkGroup = pygame.sprite.Group()
# Functions
# return an random position tuple within the bounds provided
def RandomCoordinates(width, height):
x = random.randint(0, width)
y = random.randint(0, height)
return (x, y)
# Euclidian distance
def DistanceBetweenPoints(x1, y1, x2, y2):
a = x2 - x1
b = y2 - y1
c = math.sqrt( a**2 + b**2 )
return c
def ChooseEnemyType(chance):
randomChoice = random.random()
if randomChoice > chance:
return "basic"
else:
return "red"
# spawn enemy on the given radius of the circle
def SpawnEnemy(screenDimensions, enemyImages, enemyChance):
screenWidth = screenDimensions[0]
screenHeight = screenDimensions[1]
# cast to int to avoid bug with random.randint()
minDistance = (int)(screenWidth/2 + 100)
maxDistance = (int)(minDistance + 100)
# random angle
angle = 2 * math.pi * random.random()
# random values within bounds
x = random.randint(minDistance, maxDistance)
y = random.randint(minDistance, maxDistance)
# calculate point based on given angle, and shift to be based on center of screen
ex = x * math.cos(angle) + screenWidth/2
ey = y * math.sin(angle) + screenHeight/2
# set spawn tuple
spawnPos = (ex, ey)
enemyType = ChooseEnemyType(enemyChance)
# create enemy at given position
e = Enemy(screenDimensions, spawnPos, enemyType, enemyImages)
return e
# delete old flame and create new one
def FlameReset(flamePosition, flameImageList):
flameGroup.empty()
flameGroup.add( Flame(flamePosition[0], flamePosition[1], flameImageList) )
# Send game restart signal to game state machine
def GameRestart(flamePosition, flameImageList):
enemyGroup.empty()
projectileGroup.empty()
sparkGroup.empty()
player.sprite.Restart()
FlameReset(flamePosition, flameImageList)
game.Update('r')
# Send game start signal to game state machine
def GameStart():
game.Update('space')
# Create projectile at position of player and give direction
# Only fire if delay condition is passed
def FireProjectile(screenDimensions, position, direction, lastFireTime, projectileImage, sound):
fireDelay = 500
# get current time
currentTime = pygame.time.get_ticks()
# difference between now and last shot
dt = currentTime - lastFireTime
posX = position[0]
posY = position[1]
if dt > fireDelay:
p = Projectile(screenDimensions, posX, posY, projectileImage)
if direction == "up":
p.vy = -1
if direction == "down":
p.vy = 1
if direction == "left":
p.vx = -1
if direction == "right":
p.vx = 1
projectileGroup.add(p)
# play sound
sound.play()
return currentTime
else:
# No projectile created
return lastFireTime
# Draw text to screen.
# Params:
# input: data to draw,
# posX/posY: postion of text on screen
# inFont: font of text
# screen: screen on which to draw the text
def DrawText(input, posX, posY, font, screen):
textIn = str(input)
text = font.render(textIn, True, 'white', 'black')
textRect = text.get_rect()
textRect.center = (posX, posY)
screen.blit(text, textRect)
# Shutdown pygame and exit program.
def QuitGame():
pygame.mixer.quit()
pygame.quit()
exit()
def main():
# Default window dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 608
# get user display info
USER_DISPLAY = pygame.display.Info()
# make sure window is not larger than user's display
currentScreenWidth = min(SCREEN_WIDTH, USER_DISPLAY.current_w)
currentScreenHeight = min(SCREEN_HEIGHT, USER_DISPLAY.current_h)
# dimension tuple for passing to functions
screenDimensions = (currentScreenWidth, currentScreenHeight)
# Display surface
screen = pygame.display.set_mode((currentScreenWidth, currentScreenHeight))
caption = f"Sacred Flame"
pygame.display.set_caption(caption)
screenWidthCenter = currentScreenWidth/2
screenHeightCenter = currentScreenHeight/2
# scoring
currentScore = 0
highScore = 0
# Surfaces
# Game object variables
# place pillar in the center of the screen
pillarPosX = screenWidthCenter
pillarPosY = screenHeightCenter
# place flame above pillar
flamePosX = pillarPosX
flamePosY = pillarPosY - 65
flamePosition = (flamePosX, flamePosY)
# player start position
playerSpawnPosition = (screenWidthCenter, screenHeightCenter + 200)
# Graphics
tilesize = 64
pillarImage = 'graphics/game/block.png'
flameImage = 'graphics/game/flame.png'
flameImageList = [
'graphics/game/flame/fire1_64_1.png',
'graphics/game/flame/fire1_64_3.png',
'graphics/game/flame/fire1_64_5.png',
'graphics/game/flame/fire1_64_7.png',
'graphics/game/flame/fire1_64_9.png',
'graphics/game/flame/fire1_64_11.png',
'graphics/game/flame/fire1_64_13.png',
'graphics/game/flame/fire1_64_15.png',
'graphics/game/flame/fire1_64_17.png',
'graphics/game/flame/fire1_64_19.png',
'graphics/game/flame/fire1_64_21.png',
'graphics/game/flame/fire1_64_23.png',
'graphics/game/flame/fire1_64_25.png',
'graphics/game/flame/fire1_64_27.png',
'graphics/game/flame/fire1_64_29.png',
'graphics/game/flame/fire1_64_31.png',
'graphics/game/flame/fire1_64_33.png',
'graphics/game/flame/fire1_64_35.png',
'graphics/game/flame/fire1_64_37.png',
'graphics/game/flame/fire1_64_39.png',
'graphics/game/flame/fire1_64_41.png',
'graphics/game/flame/fire1_64_43.png',
'graphics/game/flame/fire1_64_45.png',
'graphics/game/flame/fire1_64_47.png',
'graphics/game/flame/fire1_64_49.png',
'graphics/game/flame/fire1_64_51.png',
'graphics/game/flame/fire1_64_53.png',
'graphics/game/flame/fire1_64_55.png',
'graphics/game/flame/fire1_64_57.png',
'graphics/game/flame/fire1_64_59.png',
]
playerImageSet = ['graphics/player/player.png', 'graphics/player/player-dead.png']
enemyBasicImage = 'graphics/enemy/serpent-hybrid.png'
enemyRedImage = 'graphics/enemy/demon.png'
sparkImage = ['graphics/game/spark/1.png', 'graphics/game/spark/2.png', 'graphics/game/spark/3.png', 'graphics/game/spark/4.png']
projectileImage = 'graphics/magic/magic.png'
floorTile = 'graphics/game/floor-diagonal.png'
enemyImages = (enemyBasicImage, enemyRedImage)
# background
backgroundSurface = pygame.image.load(floorTile).convert_alpha()
# Add entities to groups
player.add( Player(screenDimensions, playerSpawnPosition, playerImageSet) )
objectGroup.add( GameObject(pillarPosX, pillarPosY, pillarImage) )
flameGroup.add( Flame(flamePosX, flamePosY, flameImageList) )
# Fonts
# TODO: determine final font style
defaultFont = pygame.font.SysFont('freesansbold', 32)
# Title font
titleFont = pygame.font.SysFont('freesansbold', 64)
titleText = titleFont.render("Sacred Flame", True, 'white', 'black')
titleTextRect = titleText.get_rect()
titleTextRect.center = (currentScreenWidth / 2, (currentScreenHeight / 2) - (currentScreenHeight / 6) )
# Start of game font
# startFont = pygame.font.SysFont('freesansbold', 32)
startText = defaultFont.render("Press SPACE to begin", True, 'white', 'black')
startTextRect = startText.get_rect()
startTextRect.center = (currentScreenWidth / 2, (currentScreenHeight / 2) + (currentScreenHeight / 6) )
# Pause screen font
# pauseFont = pygame.font.SysFont('freesansbold', 32)
pauseText = defaultFont.render("Game paused", True, 'white', 'black')
pauseTextRect = pauseText.get_rect()
pauseTextRect.center = (currentScreenWidth / 2, currentScreenHeight / 2)
# Player death font
# deathFont = pygame.font.SysFont('freesansbold', 32)
deathText = defaultFont.render("You Died", True, 'white', 'black')
deathTextRect = deathText.get_rect()
deathTextRect.center = (currentScreenWidth / 2, currentScreenHeight / 2)
# Flame out font
# flameOutFont = pygame.font.SysFont('freesansbold', 32)
flameOutText = defaultFont.render("The Flame went out", True, 'white', 'black')
flameOutTextRect = flameOutText.get_rect()
flameOutTextRect.center = (currentScreenWidth / 2, currentScreenHeight / 2)
# Sounds
spellSound = pygame.mixer.Sound('audio/spell-cast-low-pitch.wav')
spellSound.set_volume(0.5)
sparkPickupSound = pygame.mixer.Sound('audio/fire-flare.wav')
playerDeathSound = pygame.mixer.Sound('audio/sine-wave-dissipate-low.wav')
redDemonSound = pygame.mixer.Sound('audio/monster-sound-big-death.wav')
serpentSound = pygame.mixer.Sound('audio/monster-sound-medium-death.wav')
magicImpact = pygame.mixer.Sound('audio/magic-explosion.wav')
magicImpact.set_volume(0.7)
# Clock and timers
clock = pygame.time.Clock()
timeFactor = 100
flameTimerMax = 60 #TODO: determine time limit
# Enemy spawning timer
enemyTimer = pygame.USEREVENT + 1
enemyTimerRate = 1500
pygame.time.set_timer(enemyTimer, enemyTimerRate)
# Flame timer
flameTimer = pygame.USEREVENT + 2
flameTimerRate = 500
pygame.time.set_timer(flameTimer, flameTimerRate)
# projectile cooldown timer
projectileCooldownTimer = pygame.USEREVENT + 3
projectileCooldownTimerRate = 2000
pygame.time.set_timer(projectileCooldownTimer, projectileCooldownTimerRate)
# Timer functions
startTime = int(pygame.time.get_ticks() / timeFactor)
lastFireTime = startTime
flameTimeCurrent = flameTimerMax
# Begin main game loop
while True:
# Begin event loop
# Get event from queue
for event in pygame.event.get():
# on window close
if event.type == pygame.QUIT:
QuitGame()
# On keypress
if event.type == pygame.KEYDOWN:
# Close window on escape press
if event.key == pygame.K_q:
if game.currentState != 'running':
# Only accept close escape game input if game is not in the running state
QuitGame()
if event.key == pygame.K_SPACE:
if game.currentState == 'title':
GameStart()
if event.key == pygame.K_ESCAPE:
# pause game
game.Update('esc')
if event.key == pygame.K_r:
if game.currentState == 'playerDead' or game.currentState == 'darkness':
highScore = max( currentScore, highScore)
currentScore = 0
flameTimeCurrent = flameTimerMax
GameRestart(flamePosition, flameImageList)
# get player input
if game.IsRunning():
if event.key == pygame.K_UP:
lastFireTime = FireProjectile(screenDimensions, (player.sprite.rect.center[0], player.sprite.rect.center[1]), "up", lastFireTime, projectileImage, spellSound)
if event.key == pygame.K_DOWN:
lastFireTime = FireProjectile(screenDimensions, (player.sprite.rect.center[0], player.sprite.rect.center[1]), "down", lastFireTime, projectileImage, spellSound)
if event.key == pygame.K_LEFT:
lastFireTime = FireProjectile(screenDimensions, (player.sprite.rect.center[0], player.sprite.rect.center[1]), "left", lastFireTime, projectileImage, spellSound)
if event.key == pygame.K_RIGHT:
lastFireTime = FireProjectile(screenDimensions, (player.sprite.rect.center[0], player.sprite.rect.center[1]), "right", lastFireTime, projectileImage, spellSound)
# carrier enemy spawn increases with a lower flame
enemyChance = 1 - (flameTimeCurrent / flameTimerMax)
# spawn enemy on timer
if event.type == enemyTimer and game.IsRunning():
enemy = SpawnEnemy(screenDimensions, enemyImages, enemyChance)
enemyGroup.add(enemy)
# Decrement flame timer on tick
if event.type == flameTimer and game.IsRunning():
flameTimeCurrent -= 1
# End event loop
# Logical updates
if game.IsRunning():
currentTime = int(pygame.time.get_ticks() / timeFactor) - startTime
player.update()
projectileGroup.update()
enemyGroup.update(player)
sparkGroup.update()
flameGroup.update()
# Check flame timer
if flameTimeCurrent <= 0:
game.Update('flameOut')
# Collisions
# TODO: make this into functions
# Check collision between projectiles and enemies, and delete both on collision.
# groupcollide(group1, group2, dokill1, dokill2) -> Sprite_dict
projectileCollision = pygame.sprite.groupcollide(enemyGroup, projectileGroup, True, True)
# loop through sprites in returned sprite dict
for sprite in projectileCollision:
# play sound
magicImpact.play()
# get type
enemyType = sprite.GetType()
if enemyType == 'red':
# Get position of enemy the bullet collided with
spawnX = sprite.position[0]
spawnY = sprite.position[1]
# create spark object
sparkGroup.add( Spark(spawnX, spawnY, sparkImage) )
# increase score
currentScore += 150
if enemyType == 'basic':
# increase score
currentScore += 100
# Check collision between enemy and player.
# spritecollideany(sprite, group) -> Sprite
playerCollision = pygame.sprite.spritecollideany(player.sprite, enemyGroup)
# Deal damage to player on collision
if playerCollision != None:
player.sprite.TakeDamage(1)
# check if player has died after collision
if not player.sprite.IsAlive():
game.Update('death')
playerDeathSound.play()
# check collision between player and spark
sparkCollision = pygame.sprite.spritecollide(player.sprite, sparkGroup, True)
if sparkCollision:
sparkPickupSound.play()
flameTimeCurrent += 5
# keep flame timer below or equal to maximum
if flameTimeCurrent > flameTimerMax:
flameTimeCurrent = flameTimerMax
# Graphical updates
# tile the background
for widthPos in range(0,currentScreenWidth, tilesize):
for heightPos in range(0, currentScreenHeight, tilesize):
screen.blit(backgroundSurface, (widthPos+1, heightPos))
# Entities
objectGroup.draw(screen)
sparkGroup.draw(screen)
projectileGroup.draw(screen)
enemyGroup.draw(screen)
flameGroup.draw(screen)
player.draw(screen)
# update scale for flame
flameFraction = flameTimeCurrent / flameTimerMax
flameScaleFactor = 2
flameGroup.sprite.SetSize(flameFraction * flameScaleFactor)
# whole number percent
flamePercent = int(flameFraction * 100)
# Text
# show flame percent on screen
# TODO: remove this in final version
"""
drawThis = str(flamePercent) + "%"
DrawText(drawThis, 100, 50, defaultFont, screen)
"""
# Show score
DrawText(f"score: {currentScore}", 650, 50, defaultFont, screen)
DrawText(f"high: {highScore}", 650, 100, defaultFont, screen)
# If on the title screen
if game.IsTitle():
screen.blit(titleText, titleTextRect)
screen.blit(startText, startTextRect)
# If game is paused
if game.IsPaused():
screen.blit(pauseText, pauseTextRect)
# If player dies
if game.PlayerIsDead():
screen.blit(deathText, deathTextRect)
# If flame goes out
if game.IsDarkness():
screen.blit(flameOutText, flameOutTextRect)
# Update display surface
pygame.display.update()
# Tick speed
clock.tick(60)
main()