-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1404 lines (1181 loc) · 52.3 KB
/
main.py
File metadata and controls
1404 lines (1181 loc) · 52.3 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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import textwrap
from cmu_graphics import *
from Sprites import *
import random
from loadSound import *
import pyaudio
import numpy as np
from scipy.signal import find_peaks
from frequencyDetection import *
from colors import *
from spells import *
from animations import *
INSTRUCTIONS = ['Pay attention to these instructions. Press right arrow key to move to next. To skip (not recommended), press "E".',
'Your objective as of right now is to discover all the color combinations for the spells around this apartment',
'You can do so by interacting with objects in this environment, which will give you clues as to what those color combinations are',
'Pressing "E" on your keyboard will allow you to interact with these objects',
'Interacting with the right objects will give you access to specific spells (but right now you don\'t have access to any)',
'To cast spells, you must record a specific combination of colors',
'Notice, there\'s a cooldown bar for the spells you cast on the top left corner',
'To begin recording your color input, press "C", and to finish giving color input, press "C" again. If that combination corresponds to a spell, it will be cast.',
'After pressing "C" to record, you must switch between colors to record a specific color combination. In pressing "C" once more, the combination recorded will be evaluated.',
'You can switch between colors with your voice. The higher your voice goes, the further up in the color meter it will go (top left corner of screen) and vice versa.',
'It is recommended to sing in falsetto and around the note G4 and above to get more accurate voice detections',
'To open/close microphone, press "R". Try it',
'There are two circles on the bottom right of the screen. The left circle shows if mic is open/closed (red/gray). The one on the right shows if a note was detected (green if yes, red if no)',
'If you are having difficulties with the voice detection, close your microphone and use the arrow keys to give your color input (more info in controls screen)',
'For more information about controls, press "esc" to pause and access controls screen.',
'Good Luck!']
SOUNDS = {'castFireball':loadSound('./Sound/castFireball.mp3'),
'castFreeze':loadSound('./Sound/castFreeze.mp3'),
'heal':loadSound('./Sound/heal.mp3'),
'dash':loadSound('./Sound/dash.mp3'),
'fireball':loadSound('./Sound/flyingFireball.mp3'),
'freeze':loadSound('./Sound/freeze.mp3'),
'death':loadSound('./Sound/death.mp3'),
'takeDamage-1':loadSound('./Sound/takeDamage-1.mp3'), 'takeDamage-2':loadSound('./Sound/takeDamage-2.mp3'),
'explosion':loadSound('./Sound/explosion.mp3'),
'zombieTakeDamage':loadSound('./Sound/zombieTakeDamage.mp3'),
'zombieDeath':loadSound('./Sound/zombieDeath.mp3'),
'walk':loadSound('./Sound/walk.mp3'),
'gameover':loadSound('./Sound/gameover.mp3'),
'click':loadSound('./Sound/click.mp3'),
'titleSong':loadSound('./Sound/titleSong.mp3'),
'battleMusic':loadSound('./Sound/testBattleMusic.mp3')}
def empty_function(app=None, a=None, b=None, c=None):
pass
def distance(x1, y1, x2, y2):
return ((x1-x2)**2 + (y1-y2)**2)**0.5
def roundInt(x1):
base = int(x1)
if(base == 0):
base = 1
if((x1%base) > 0.5):
return base+1
return int(x1)
def listFind(L, obj):
index = -1
try:
index = L.index(obj)
except ValueError:
return -1
return index
class Effect:
def __init__(self, spritesheet, x, y, radius=None, areaColor=None):
self.x = x
self.y = y
self.radius = radius
self.curSprite = openAnimation(spritesheet[0], spritesheet[1])
self.spriteIndex = 0
self.spriteRate = None if(spritesheet == None) else spritesheet[2]
self.spriteSize = None if(spritesheet == None) else (spritesheet[3], spritesheet[4])
self.areaColor = areaColor
def __eq__(self, other):
if(isinstance(other, Effect)):
return ((self.x, self.y) == (other.x, other.y) and self.curSprite == other.curSprite)
return False
def drawArea(self, app):
if(self.radius != None):
drawCircle(self.x - app.camX, self.y - app.camY, self.radius, border='black', opacity=40, fill=self.areaColor)
def draw(self,app):
if(self.curSprite[0][:-2] in EFFECTSPRITES):
stopIndex = self.curSprite[self.spriteIndex].find('-')
drawImage(f'./Sprites/{self.curSprite[self.spriteIndex][:stopIndex]}/{self.curSprite[self.spriteIndex]}.png', self.x - app.camX, self.y - app.camY, width=self.spriteSize[0], height=self.spriteSize[1], align='center')
def updateAnimation(self, app):
if(self.curSprite == None):
return
if(self.spriteIndex >= len(self.curSprite)-1):
self.destroy(app)
return
rate = app.stepsPerSecond // self.spriteRate
if(app.step % rate == 0):
self.spriteIndex = (self.spriteIndex + 1) % len(self.curSprite)
def destroy(self, app):
index = listFind(app.map.effects, self)
if(index != -1):
app.map.effects.pop(index)
class map:
def __init__(self, blockSize = app.width):
self.blockSize = blockSize
self.objects = []
self.enemies = []
self.projectiles = []
self.objectBlocks = dict()
self.enemyBlocks = dict()
self.effects = []
self.messages = []
self.spawners = []
def addObject(self, object):
if(isinstance(object, MapObject)):
self.objects.append(object)
edges = object.getEdges()
blocks = set()
for edge in edges:
x,y = edge
block = self.getBlock(x,y)
if(block not in blocks):
blocks.add(block)
self.objectBlocks[block] = self.objectBlocks.get(block, set())
self.objectBlocks[block].add(object)
def addEnemy(self, enemy):
if(isinstance(enemy, Enemy)):
enemy.setID(len(self.enemies))
self.enemies.append(enemy)
edges = enemy.getEdges()
blocks = set()
for edge in edges:
x,y = edge
block = self.getBlock(x,y)
if(block not in blocks):
blocks.add(block)
self.enemyBlocks[block] = self.enemyBlocks.get(block, set())
self.enemyBlocks[block].add(object)
def addSpawner(self, spawner):
if(isinstance(spawner, Spawner)):
self.spawners.append(spawner)
def addEffect(self, effect):
if(isinstance(effect, Effect)):
self.effects.append(effect)
def addMessage(self, message):
if(isinstance(message, Message)):
self.messages.append(message)
def addProjectile(self, projectile):
self.projectiles.append(projectile)
def moveProjectiles(self, app):
for projectile in self.projectiles:
projectile.move(app)
for enemy in self.enemies:
projectile.checkCollision(app, enemy)
blocks = self.getBlocks([(projectile.x, projectile.y), (projectile.x+(projectile.radius*2), projectile.y), (projectile.x, projectile.y+(projectile.radius)*2), (projectile.x+(projectile.radius*2), projectile.y+(projectile.radius*2))])
for block in blocks:
for object in self.objectBlocks.get(block, []):
projectile.checkCollision(app, object)
def getBlocks(self, edgeList):
blockList = set()
for edge in edgeList:
x,y = edge
blockList.add(self.getBlock(x,y))
return blockList
def getBlock(self, x, y):
signX = 1
signY = 1
if(x < 0):
signX = -1
if(y < 0):
signY = -1
x = abs(x)
y = abs(y)
blockX = signX * ((x // self.blockSize) + 1)
blockY = signY * ((y // self.blockSize) + 1)
return (int(blockX), int(blockY))
def checkAllObjectCollision(self, other):
blocks = self.getBlocks(other.getEdges())
hasCollided = False
for block in blocks:
for object in self.objectBlocks.get(block, []):
if(object.checkCollision(other)):
hasCollided = True
return hasCollided
def checkAllEnemiesCollision(self, other):
for enemy in self.enemies:
if(enemy.checkCollision(other)):
return enemy
return None
def checkInteraction(self, app, other, radius):
blocks = self.getBlocks(other.getEdges())
hasCollided = False
for block in blocks:
for object in self.objectBlocks.get(block, []):
for dx in {radius, -radius}:
if(object.checkCollision((other.x+dx, other.y, other.width, other.height))):
object.interact(app, other)
return (True, object)
for dy in {radius, -radius}:
if(object.checkCollision((other.x, other.y+dy, other.width, other.height))):
object.interact(app, other)
return (True, object)
return (False,)
def checkHit(self, other, radius):
otherX, otherY, otherWidth, otherHeight = other
blocks = self.getBlocks([(otherX, otherY)])
hasCollided = False
for block in blocks:
for object in self.objectBlocks.get(block, []):
for dx in {radius, -radius}:
if(object.checkCollision((otherX+dx, otherY, otherWidth, otherHeight))):
return True
for dy in {radius, -radius}:
if(object.checkCollision((otherX, otherY+dy, otherWidth, otherHeight))):
return True
def enemiesFollowPlayer(self, app):
for enemy in self.enemies:
enemy.followPlayer(app)
def trackEnemies(self, app, secondsPassed):
for enemy in self.enemies:
enemy.moveAwayFromEnemies(app)
enemy.trackZap(secondsPassed)
def runSpawners(self, app, secondsPassed):
for spawner in self.spawners:
spawner.runSpawner(app, secondsPassed)
def updateAnimations(self, app):
for enemy in self.enemies:
enemy.updateAnimation(app)
for effect in self.effects:
effect.updateAnimation(app)
def changeMessages(self, delta):
for message in self.messages:
if(message.display):
message.changeMessage(delta)
def draw(self, app):
drawImage('./Sprites/map.png', -app.camX, -app.camY) #Credit for spritesheet used to make the map: https://limezu.itch.io/
for effect in self.effects:
effect.drawArea(app)
for obj in self.objects:
obj.draw(app)
app.player.draw(app)
for enemy in self.enemies:
enemy.draw(app)
for projectile in self.projectiles:
projectile.draw(app)
for effect in self.effects:
effect.draw(app)
for message in self.messages:
message.draw()
class MapObject:
def __init__(self, x, y, height = None, width = None, radius = None, color = None, shape = None, sprite=None, interaction=empty_function):
self.color = color
self.x = x
self.y = y
self.radius = radius
self.height = height
self.width = width
if(sprite != None):
self.sprite = OBJECTSPRITES[sprite]
if(radius != None):
self.height = radius*2
self.width = radius*2
self.shape = shape
self.edges = self.getEdges()
self.interaction = interaction
def __repr__(self):
return f'<MapObject: {self.shape} at ({self.x}, {self.y})>'
def draw(self, app):
if(self.shape == 'circle'):
if(self.color == None): return
drawCircle(self.x - app.camX, self.y - app.camY, self.radius, fill=self.color, align='top-left')
elif(self.shape == 'rect'):
if(self.color == None): return
drawRect(self.x - app.camX, self.y - app.camY, self.width, self.height, fill=self.color)
elif(self.shape == 'image'):
drawImage(f'./Sprites/objects/{self.sprite}.png', self.x-app.camX, self.y-app.camY, width=self.width, height=self.height)
def getEdges(self):
curList = [(self.x, self.y), (self.x + self.width, self.y), (self.x, self.y - self.height), (self.x + self.width, self.y + self.height)]
for pos in range(self.x, self.x+self.width, 32):
curList.extend([(pos, self.y), (pos, self.y+self.height)])
for pos in range(self.y, self.y+self.height, 32):
curList.extend([(self.x, pos), (self.x+self.width, pos)])
return curList
def checkCollision(self, other):
if(isinstance(other, tuple)):
otherX, otherY, otherWidth, otherHeight = other
else:
otherX, otherY, otherWidth, otherHeight = other.x, other.y, other.width, other.height
withinXBounds = False
for x in {otherX, otherX + otherWidth}:
if(self.x < x < self.x+self.width):
withinXBounds = True
if(not withinXBounds):
return False
for y in {otherY, otherY + otherHeight}:
if(self.y < y < self.y + self.height):
self.collide(other)
return True
def collide(self, other):
pass
def interact(self, app, other):
self.interaction(app)
def stopInteraction(self, app):
pass
class ReadableObject(MapObject):
def __init__(self, x, y, height = None, width = None, radius = None, color = None, shape = None, sprite=None, interaction=empty_function, message=['']):
super().__init__(x, y, height, width, radius, color, shape, sprite, interaction)
self.message = message
def interact(self, app, other):
super().interact(app, other)
app.textBox.displayMessage(self.message)
def stopInteraction(self, app):
app.textBox.stopDisplay()
class Enemy:
def __init__(self, x, y, width, height, speed=2):
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.width = width
self.height = height
self.edges = self.getEdges()
self.sprites = ZOMBIESPRITES
self.curSprite = openAnimation(self.sprites['idle'][0], self.sprites['idle'][1])
self.curAnim = 'idle'
self.spriteIndex = 0
self.spriteRate = self.sprites['idle'][2]
self.speed = speed
self.visionLimit = 300
self.visionBlocked = True
self.confused = False
self.health = 4
self.id = None
self.defaultColor = RGBZOMBIE
self.color = [self.defaultColor[0], self.defaultColor[1], self.defaultColor[2]]
self.zapped = False
self.zapTimer = 0
def setID(self, id):
self.id = id
def __eq__(self, other):
if(isinstance(other, Enemy)):
if(other.id == None or self.id == None):
return False
return self.id == other.id
return False
def draw(self, app):
sprite = 'zombie_idle-1'
if(0 <= self.spriteIndex < len(self.curSprite)):
sprite = self.curSprite[self.spriteIndex]
drawImage(f'./Sprites/{sprite[:-2]}/{sprite}.png', self.x - app.camX, self.y - app.camY, width=32, height=32)
def updateAnimation(self, app):
if(self.zapped):
return
rate = app.stepsPerSecond // self.spriteRate
if(app.step % rate == 0):
self.spriteIndex = (self.spriteIndex + 1) % len(self.curSprite)
self.checkMovement()
def checkMovement(self):
if(self.dy > 0):
anim = 'forwards'
elif(self.dy < 0):
anim = 'backwards'
elif(self.dx > 0):
anim = 'right'
elif(self.dx < 0):
anim = 'left'
else:
anim = 'idle'
if(anim != self.curAnim):
self.setAnimation(anim)
def setAnimation(self, animation):
self.curAnim = animation
self.curSprite = openAnimation(self.sprites[animation][0], self.sprites[animation][1])
self.spriteRate = self.sprites[animation][2]
def dealDamage(self, app, other):
other.takeDamage(app, 1)
def takeDamage(self, app, damage):
self.health -= damage
app.map.addEffect(Effect(('blood', 26, 30, 100, 100), self.x + self.width/2, self.y + self.height/2))
if(self.health <= 0):
self.death(app)
else:
SOUNDS['zombieTakeDamage'].play(restart=True)
def zap(self):
self.zapped = True
self.zapTimer = 3
def trackZap(self, secondsPassed):
if(self.zapped):
if(self.zapTimer <= 0):
self.zapped = False
else:
self.zapTimer -= secondsPassed
def death(self, app):
SOUNDS['zombieDeath'].play(restart=True)
if self in app.map.enemies:
app.map.enemies.remove(self)
def interact(self, app):
app.map.checkInteraction(self, self.speed)
def __repr__(self):
return f'<Enemy w/ id={self.id} at {(self.x, self.y)}>'
def getEdges(self):
return [(self.x, self.y), (self.x + self.width, self.y), (self.x, self.y - self.height), (self.x + self.width, self.y + self.height)]
def followPlayer(self, app):
if(self.zapped):
return
if(app.step % 30 == 0):
if(self.canSee(app, app.player)):
self.visionBlocked = False
else:
self.visionBlocked = True
if(self.visionBlocked):
return
target = (app.player.x, app.player.y)
distanceToTarget = ((target[0]-self.x)**2 + (target[1]-self.y)**2)**0.5
dx = (self.speed/distanceToTarget) * (target[0]-self.x)
dy = (self.speed/distanceToTarget) * (target[1]-self.y)
self.move(app, dx, dy)
def checkCollision(self, other):
if(isinstance(other, tuple)):
otherX, otherY, otherWidth, otherHeight = other
else:
otherX, otherY, otherWidth, otherHeight = other.x, other.y, other.width, other.height
withinXBounds = False
for x in {otherX, otherX + otherWidth}:
if(self.x <= x <= self.x+self.width):
withinXBounds = True
if(not withinXBounds):
return False
for y in {otherY, otherY + otherHeight}:
if(self.y <= y <= self.y + self.height):
self.collide(other)
return True
def collide(self, other):
pass
def move(self, app, dx, dy):
self.dx, self.dy = dx, dy
self.x += dx
if(not(dx == 0)):
if(app.map.checkAllObjectCollision(self) or self.checkCollisionWithPlayer(app)):
self.x -= dx
self.dx = 0
self.y += dy
if(not(dy == 0)):
if(app.map.checkAllObjectCollision(self) or self.checkCollisionWithPlayer(app)):
self.y -= dy
self.dy = 0
def moveAwayFromEnemies(self, app):
collision = app.map.checkAllEnemiesCollision(self)
if(self.id == collision.id):
return
change = (0, 0)
speed = 1
if(collision != None):
if(self.x <= collision.x):
self.x -= speed
change = (change[0]-speed, change[1])
else:
self.x += speed
change = (change[0] + speed, change[1])
if(self.y <= collision.y):
self.y -= speed
change = (change[0], change[1] -speed)
else:
self.y += speed
change = (change[0], change[1] + speed)
if (app.map.checkAllObjectCollision(self) or self.checkCollisionWithPlayer(app)):
self.x -= change[0]
self.y -= change[0]
def checkCollisionWithPlayer(self,app):
if(self.checkCollision(app.player)):
self.dealDamage(app, app.player)
def canSee(self, app, other):
self.dx = 0
self.dy = 0
tileSize = 32
selfX, selfY = self.x + self.width/2, self.y + self.height/2
otherX, otherY = other.x + other.width/2, other.y + other.height/2
distX = otherX - selfX
distY = otherY - selfY
dist = distance(selfX, selfY, otherX, otherY)
if(dist <= 1):
return True
dir = (distX/dist, distY/dist)
normX, normY = 1,1
if(otherX < selfX): normX = -1
if(otherY < selfY): normY = -1
if(dist < self.visionLimit):
curCheck = (selfX, selfY)
while True:
distToX = normX*curCheck[0] % tileSize
distToY = normY*curCheck[1] % tileSize
distToX = tileSize - distToX
distToY = tileSize - distToY
distXToEdge = distToX
distYToEdge = distToY
if(distX != 0):
distXToEdge = distance(0, 0, distToX, distToX*(distY/distX))
if(distY != 0):
distYToEdge = distance(0, 0, distToY*(distX/distY), distToY)
if distXToEdge < distYToEdge:
ratio = 0
if(dir[0] != 0):
ratio = abs(dir[1] / dir[0])
curCheck = (curCheck[0] + (normX*distToX), curCheck[1] + normY * (distToX * ratio))
else:
ratio = 0
if(dir[1] != 0):
ratio = abs(dir[0] / dir[1])
curCheck = (curCheck[0] + normX*(distToY * ratio), curCheck[1] + (normY*distToY))
curCheck = (roundInt(curCheck[0]), roundInt(curCheck[1]))
if(distance(self.x, self.y, curCheck[0], curCheck[1]) > dist):
return True
if app.map.checkHit((curCheck[0], curCheck[1], 1, 1), 1):
return False
else:
return False
class Player:
def __init__(self, x, y, width, height, sprites, speed=3):
self.x = x
self.y = y
self.prevX = x
self.prevY = y
self.moving = False
self.dx = 0
self.dy = 0
self.trueDx = 0
self.trueDy = 0
self.width = width
self.height = height
self.sprites = sprites
self.curSprite = openAnimation(sprites['idle'][0], sprites['idle'][1])
self.curAnim = 'idle'
self.spriteIndex = 0
self.spriteRate = sprites['idle'][2]
self.speed = speed
self.health = 10
self.healthBarColor = 'red'
self.isImmune = False
self.immunityTimer = 0
self.isDashing = False
self.dashTimer = 0
self.isInteracting = False
self.interactionObject = None
def draw(self, app):
sprite = 'wizard_idle-1'
if(0 <= self.spriteIndex < len(self.curSprite)):
sprite = self.curSprite[self.spriteIndex]
drawImage(f'./Sprites/{sprite[:-2]}/{sprite}.png', self.x - app.camX, self.y - app.camY)
def updateAnimation(self, app):
rate = app.stepsPerSecond // self.spriteRate
if(app.step % rate == 0):
self.spriteIndex = (self.spriteIndex + 1) % len(self.curSprite)
self.checkMovement()
def setAnimation(self, animation):
self.curAnim = animation
self.curSprite = openAnimation(self.sprites[animation][0], self.sprites[animation][1])
self.spriteRate = self.sprites[animation][2]
def drawHealthBar(self, x, y, height):
if(self.health >= 1):
drawRect(x, y, 100, height, fill='white')
drawRect(x, y, self.health*10, height, fill=self.healthBarColor)
drawRect(x, y, 100, height, fill=None, border='black', borderWidth=4)
def takeDamage(self, app, damage):
soundIndex = int(random.random()*2) + 1
if(not self.isImmune):
self.health -= damage
SOUNDS[f'takeDamage-{soundIndex}'].play(restart=True)
self.startImmunity()
if(self.health <= 0):
self.death(app)
def startImmunity(self):
self.isImmune = True
self.immunityTimer = 2
def checkImmunity(self, secondsPassed):
self.immunityTimer -= secondsPassed
if(self.healthBarColor == 'red'):
self.healthBarColor = 'white'
else:
self.healthBarColor = 'red'
if(self.immunityTimer <= 0):
self.isImmune = False
self.healthBarColor = 'red'
def dash(self):
SOUNDS['dash'].play(restart=True)
self.speed *= 2
self.dashTimer = 0.5
self.isDashing = True
def trackDash(self, secondsPassed):
if(self.isDashing):
self.dashTimer -= secondsPassed
if(self.dashTimer < 0):
self.isDashing = False
self.speed //= 2
def fireball(self, app):
app.map.projectiles.append(Fireball(self.x + self.width/2, self.y + self.height/2, self.dx*3, self.dy*3, Enemy))
SOUNDS['castFireball'].play(restart=True)
SOUNDS['fireball'].play(restart=True, loop=True)
def freeze(self, app):
SOUNDS['freeze'].play(restart=True)
SOUNDS['castFreeze'].play(restart=True)
for enemy in app.map.enemies:
if(distance(self.x, self.y, enemy.x + enemy.width/2, enemy.y + enemy.height/2) < 90):
enemy.takeDamage(app, 2)
enemy.zap()
app.map.addEffect(Effect(('freeze', 6, 3, 64, 64), self.x + self.width/2, self.y + self.height/2, radius=90, areaColor=rgb(138, 138, 255)))
def heal(self, app):
SOUNDS['heal'].play(restart=True)
if(self.health < 10):
self.health += 1
def move(self, app, keys):
if(app.textBox.display):
return
dx = 0
dy = 0
if('w' in keys):
dy -= self.speed
if('a' in keys):
dx -= self.speed
if('s' in keys):
dy += self.speed
if('d' in keys):
dx += self.speed
self.trueDx = dx
self.trueDy = dy
if(not(dx == 0 and dy == 0)):
self.dx = dx
self.dy = dy
self.x += dx
app.camX += dx
if(not(dx == 0)):
if(app.map.checkAllObjectCollision(self)):
app.camX -= dx
self.x -= dx
self.y += dy
app.camY += dy
if(not(dy == 0)):
if(app.map.checkAllObjectCollision(self)):
app.camY -= dy
self.y -= dy
def checkMovement(self):
if(self.moving):
if(almostEqual(self.x, self.prevX) and almostEqual(self.y, self.prevY)):
self.moving = False
elif(not (almostEqual(self.x, self.prevX) and almostEqual(self.y, self.prevY))):
self.moving = True
self.prevX = self.x
self.prevY = self.y
if(self.moving):
if(self.x == self.prevX and self.y == self.prevY):
self.moving = False
if(self.dy > 0):
anim = 'forwards'
elif(self.dy < 0):
anim = 'backwards'
elif(self.dx > 0):
anim = 'right'
elif(self.dx < 0):
anim = 'left'
else:
anim = 'idle'
if(anim != self.curAnim):
self.setAnimation(anim)
def interact(self, app):
if(not self.isInteracting):
interaction = app.map.checkInteraction(app, self, self.speed)
if(interaction[0]):
self.isInteracting = True
self.interactionObject = interaction[1]
else:
self.interactionObject.stopInteraction(app)
self.interactionObject = None
self.isInteracting = False
def __repr__(self):
return f'<Player at {(self.x, self.y)}>'
def getEdges(self):
return [(self.x, self.y), (self.x + self.width, self.y), (self.x, self.y - self.height), (self.x + self.width, self.y + self.height)]
def castSpell(self, app, spell):
cast(app, self, spell)
def death(self, app):
app.gameoverMessage = 'You died...'
gameover(app)
class Projectile:
def __init__(self, x, y, dx, dy, targetType):
self.x = x
self.y = y
self.radius = 3
self.dx = dx
self.dy = dy
self.targetType = targetType
def __repr__(self):
return f'<Projectile at {(self.x, self.y)}>'
def __eq__(self, other):
if(isinstance(other, Projectile)):
return (self.x, self.y, self.radius) == (other.x, other.y, other.radius)
return False
def draw(self, app):
drawCircle(self.x - app.camX, self.y-app.camY, self.radius, align='top-left', fill='black')
def move(self, app):
self.x += self.dx
self.y += self.dy
if(not ((-100 < self.x - app.camX < app.width + 100) and (-100 < self.y - app.camY < app.height + 100))):
self.destroy(app)
def checkCollision(self, app, other):
hasCollided = False
if(isinstance(other, MapObject)):
if(other.checkCollision((self.x, self.y, self.radius, self.radius))):
hasCollided = True
self.objectCollide(app, other)
elif(isinstance(other, Enemy)):
if(other.checkCollision((self.x, self.y, self.radius, self.radius))):
hasCollided = True
self.enemyCollide(app, other)
return hasCollided
def objectCollide(self, app, object):
self.destroy(app)
def enemyCollide(self, app, enemy):
enemy.takeDamage(app, 5)
self.destroy(app)
def destroy(self, app):
index = listFind(app.map.projectiles, self)
if(index != -1):
app.map.projectiles.pop(index)
class Fireball(Projectile):
def __init__(self, x, y, dx, dy, targetType):
super().__init__(x, y, dx, dy, targetType)
self.radius = 5
def enemyCollide(self, app, enemy):
enemy.takeDamage(app, 5)
self.destroy(app)
def draw(self, app):
drawCircle(self.x - app.camX, self.y-app.camY, self.radius, align='top-left', fill='red')
def destroy(self, app):
SOUNDS['fireball'].pause()
SOUNDS['explosion'].play(restart=True)
for localEnemy in app.map.enemies:
dist = distance(self.x, self.y, localEnemy.x + localEnemy.width/2, localEnemy.y + localEnemy.height/2)
if(dist < 30):
localEnemy.takeDamage(app, 5)
elif(dist < 50):
localEnemy.takeDamage(app, 3)
app.map.addEffect(Effect(('explosion', 6, 3, 30, 30), self.x, self.y, 50, areaColor=rgb(255, 138, 138)))
index = listFind(app.map.projectiles, self)
if(index != -1):
app.map.projectiles.pop(index)
class Message:
def __init__(self, x, y, width, height, fontSize):
self.x = x
self.y = y
self.width = width
self.height = height
self.messages = []
self.messageIndex = 0
self.lines = []
self.display = False
self.fontSize = fontSize
def displayMessage(self, messages):
self.display = True
self.messages = messages
self.messageIndex = 0
self.lines = self.findLines(messages[self.messageIndex])
def changeMessage(self, delta):
if(0 <= self.messageIndex+delta < len(self.messages)):
self.messageIndex += delta
self.lines = self.findLines(self.messages[self.messageIndex])
def stopDisplay(self):
self.display = False
self.message = ''
self.messageIndex = 0
self.lines = None
def findLines(self, message):
lines = []
charsPerLine = int(self.width/10)
pixels = self.x + len(message) * (self.fontSize/2.2)
lineCount = len(message) // charsPerLine
if(lineCount > 0):
charsPerLine = len(message) // lineCount
for i in range(lineCount):
lines.append(message[i*charsPerLine:(i+1)*charsPerLine])
lines.append(message[lineCount*charsPerLine:])
return textwrap.fill(message, 60).splitlines()
def draw(self):
if(self.display):
drawRect(self.x - 10, self.y - 10, self.width, self.height, border='black', borderWidth=4, fill='white', opacity=90)
for i in range(len(self.lines)):
drawLabel(self.lines[i], self.x, i*20 + self.y, size=self.fontSize, align='top-left')
backText = ''
nextText = 'press "E"'
if(self.messageIndex > 0):backText = '<-- back'
if(self.messageIndex < len(self.messages)-1): nextText = 'next -->'
drawLabel(backText, self.x + 10, self.y + self.height - 30, align='top-left')
drawLabel(nextText, self.x + self.width - 70, self.y + self.height - 30, align='top-left')
class Spawner:
def __init__(self, x, y, spawnRate, maxSpawn):
self.x = x
self.y = y
self.spawnRate=spawnRate
self.timer = 0
self.maxSpawn = maxSpawn
def spawn(self, app):
app.map.addEnemy(Enemy(self.x, self.y, 32, 32))
def runSpawner(self, app, secondsPassed):
self.timer += secondsPassed
if(self.timer >= self.spawnRate):
if(distance(app.player.x, app.player.y, self.x, self.y) < 160):
return
self.timer = 0
if len(app.map.enemies) < self.maxSpawn:
self.spawn(app)
def gameover(app):
SOUNDS['battleMusic'].play()
SOUNDS['battleMusic'].pause()
SOUNDS['gameover'].play(restart=True)
app.gameover = True
app.paused = True
def onAppStart(app):
goToStartScreen(app)
app.onControlsScreen = False
app.onSpellsScreen = False
app.wave = 1
app.waveTimer = 0
reset(app)
app.enemyPoints = [(160, 160), (128, 192), (32, 320), (96, 320), (160, 320),
(320, 96), (416, 96), (512, 96), (320, 160), (416, 160), (512, 160),
(320, 224), (416, 224), (512, 224), (320, 288), (416, 288), (512, 288),
(320, 416), (416, 416), (512, 416), (320, 544), (416, 544), (512, 544),
(48, 576), (176, 576), (48, 672), (176, 672), (48, 768), (176, 768),
(448, 768), (512, 768), (576, 768), (640, 768), (704, 768),
(672, 224), (768, 224), (864, 224), (672, 288), (768, 288), (864, 288),
(672, 352), (768, 352)]
def startLearnMode(app):
app.onStartScreen = False
app.waveMode = False
app.learnMode = True