-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainGame.py
1407 lines (1224 loc) · 60.7 KB
/
mainGame.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
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 pygame
from math import floor, ceil
from random import randint
import os, time, sys
#Initialization
pygame.init()
WIDTH = 1400
HEIGHT = 900
display = pygame.display.set_mode((WIDTH, HEIGHT))
cwd = os.getcwd()
#Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (238, 232, 170)
WATER_BLUE = (0, 0, 130)
BEIGE = (207, 185, 151)
DARK_RED = (124, 10, 2)
FOREST_GREEN = (11, 102, 35)
OLIVE_GREEN = (96, 168, 48)
GREY = (169, 169, 169)
DARK_BEIGE = (169, 149, 123)
#Fonts
textFont = pygame.font.SysFont("Comic Sans MS", 20)
signFont = pygame.font.SysFont("ComicSans MS", 17)
storeFont = pygame.font.SysFont("Comic Sans MS", 15)
titleFont = pygame.font.SysFont("Comic Sans MS", 40)
#Grid movement in directions(Clockwise starting from 1 is upwards direction)
movement = [[], [0, -1], [1, 0], [0, 1], [-1, 0]]
#Map Information
GRID_DIST_TOP = 25
GRID_WIDTH = 40
GRID_HEIGHT = 30
SQUARE_SIZE = 25
moveableSpaces = ["/", ".", ",", "-", "I"]
areaMap = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
spawnChances = [
[],
[20, 30, 50],
[50, 50, 0],
[10, 10, 80],
[50, 40, 10],
[30, 30, 40],
[40, 50, 10],
[100, 0, 0],
[60, 30, 10],
[40, 40, 20]
]
spawnRates = [0, 3, 3, 3, 3, 3, 3, 1, 3, 3]
#Folder and file information
groundAreas = ["", "mapAreaGround1.txt", "mapAreaGround2.txt", "mapAreaGround3.txt", "mapAreaGround4.txt", "mapAreaGround5.txt", "mapAreaGround6.txt", "mapAreaGround7.txt", "mapAreaGround8.txt", "mapAreaGround9.txt"]
obstacleAreas = ["", "mapArea1.txt", "mapArea2.txt", "mapArea3.txt", "mapArea4.txt", "mapArea5.txt", "mapArea6.txt", "mapArea7.txt", "mapArea8.txt", "mapArea9.txt"]
weaponFiles = ["weaponTypes.txt", "shieldTypes.txt"]
def loadTile(fileName, width, height):
return pygame.transform.scale(pygame.image.load(os.path.join(cwd, "art", "tileArt", fileName)).convert_alpha(), (width, height))
def checkIfExitGame(events):
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Loads all the tile images
groundDict = {
"." : loadTile("grassArt.png", 25, 25),
"," : loadTile("snowArt.png", 25, 25),
"/" : loadTile("pathArt.png", 25, 25),
"!" : loadTile("charredGroundArt.png", 25, 25)
}
obstacleDict = {
"#" : loadTile("treeArt.png", 50, 50),
"%" : loadTile("waterArt.png", 25, 25),
"^" : loadTile("snowyTreeLarge.png", 50, 50),
"S" : loadTile("signArt.png", 25, 25),
"C" : loadTile("chestArt.png", 25, 25),
"T" : loadTile("smallTreeArt.png", 25, 25),
"O" : loadTile("moveableRockArt.png", 25, 25),
"I" : loadTile("iceArt.png", 25, 25),
"L" : loadTile("staticRockArtLarge.png", 50, 50),
"B" : loadTile("bushArt.png", 25, 25),
"K" : loadTile("staticRockArtSmall.png", 25, 25),
"P" : loadTile("snowyTreeSmall.png", 25, 25),
"A" : loadTile("houseA.png", 300, 175)
}
#Game information
bossDefeated = False
def loadDirectionalSprites(folder, fileName): #Image rotation results in loss of quality
sprites = [""]
for i in range(1, 5):
sprites.append(pygame.transform.scale(pygame.image.load(os.path.join(cwd, "art", folder, fileName + str(i) + ".png")).convert_alpha(), (25, 25)))
return sprites
def isInConstraint(x, lower, upper):
if x >= lower and x <= upper:
return True
else:
return False
def drawTextBoxes(text, delay, backgroundColour, name):
#Displays text from list of strings with 2 lines in every text box
for i in range(0, len(text), 2):
pygame.draw.rect(display, DARK_BEIGE, (150, 780, 1100, 40), 0)
pygame.draw.rect(display, backgroundColour, (150, 820, 1100, 65), 0)
displayName = textFont.render(name, 1, WHITE)
display.blit(displayName, (175, 784))
for k in range(2):
if i+k <= len(text) - 1:
displayText = signFont.render(text[i+k].strip(), 1, BLACK)
display.blit(displayText, (175, 825 + k*25))
pygame.display.update()
pygame.time.wait(delay)
def getScreenPos(gridX, gridY):
#Gets the position on the window from the position on the grid
screenX = gridX * SQUARE_SIZE - GRID_WIDTH*SQUARE_SIZE/2 + WIDTH/2 - SQUARE_SIZE
screenY = gridY * SQUARE_SIZE + GRID_DIST_TOP - SQUARE_SIZE
return (screenX, screenY)
def textToBool(text):
if text.strip() == "True":
return True
else:
return False
#Information container classes
class Node():
def __init__(self, f, g, h, parent, position):
self.f = f
self.g = g
self.h = h
self.parent = parent
self.position = position
class StoreItem():
def __init__(self, item, stock, cost):
self.item = item
self.stock = stock
self.cost = cost
class Button:
alreadyClicked = False
useable = True
def __init__(self, x, y, width, height, colour, text, textColour, hoverColour):
self.x = x
self.y = y
self.height = height
self.width = width
self.colour = colour
self.text = text
self.textColour = textColour
self.hoverColour = hoverColour
self.buttonFont = pygame.font.SysFont("Comic Sans MS", self.height - 14)
self.displayText = self.buttonFont.render(self.text, 1, self.textColour)
self.buttonRect = self.displayText.get_rect(center = (self.x + self.width/2, self.y + self.height/2))
def draw(self):
mouseX, mouseY = pygame.mouse.get_pos()
if (self.x <= mouseX <= self.x + self.width) and (self.y <= mouseY <= self.y + self.height) and self.useable:
pygame.draw.rect(display, self.hoverColour, (self.x, self.y, self.width, self.height), 0)
else:
pygame.draw.rect(display, self.colour, (self.x, self.y, self.width, self.height), 0)
display.blit(self.displayText, self.buttonRect)
def isHovered(self):
mouseX, mouseY = pygame.mouse.get_pos()
if (self.x <= mouseX <= self.x + self.width) and (self.y <= mouseY <= self.y + self.height):
return True
return False
def isLeftClicked(self, events):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if self.isHovered():
return True
return False
def isRightClicked(self, events):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 3:
if self.isHovered():
return True
return False
#Item classes
class Item():
def __init__(self, name, effect, sprite, throwable):
self.name = name
self.effect = effect
self.sprite = sprite
self.throwable = throwable
class StrengthPotion(Item):
def __init__(self, name, effect, sprite, throwable):
Item.__init__(self, name, effect, sprite, throwable)
def usePot(self, player):
player.addDamage += self.effect
class HealthPotion(Item):
def __init__(self, name, effect, sprite, throwable):
Item.__init__(self, name, effect, sprite, throwable)
def usePot(self, player):
player.remainingHealth += self.effect
if player.remainingHealth > player.maxHealth:
player.remainingHealth = player.maxHealth
class Shield(Item):
def __init__(self, name, effect, sprite, throwable):
Item.__init__(self, name, effect, sprite, throwable)
class Weapon(Item):
def __init__(self, name, effect, sprite, throwable):
Item.__init__(self, name, effect, sprite, throwable)
class GameObject():
def __init__(self, areaNumber):
self.areaNumber = areaNumber
class FreeMovingObject():
def __init__(self, x, y):
self.x = x
self.y = y
class Projectile(FreeMovingObject):
def __init__(self, x, y, sizeX, sizeY, speed):
FreeMovingObject.__init__(self, x, y)
self.sizeX = sizeX
self.sizeY = sizeY
self.speed = speed
def isContact(self, player):
playerCornerLocations = []
playerCornerLocations.append((player.x, player.y))
playerCornerLocations.append((player.x + 50, player.y))
playerCornerLocations.append((player.x, player.y + 50))
playerCornerLocations.append((player.x + 50, player.y + 50))
for i in playerCornerLocations:
if self.x <= i[0] <= self.x + self.sizeX and self.y <= i[1] <= self.y + self.sizeY:
return True
return False
def draw(self):
display.blit(self.sprite, (self.x, self.y))
class ZombieProjectile(Projectile):
def __init__(self, x, y, sizeX, sizeY, speed):
Projectile.__init__(self, x, y, sizeX, sizeY, speed)
self.destX = 0 - self.sizeX
self.sprite = loadTile("zombieProj.png", self.sizeX, self.sizeY)
def move(self):
self.x -= self.speed
def finished(self):
if self.x < self.destX:
return True
return False
class BookProjectile(Projectile):
def __init__(self, x, y, sizeX, sizeY, speed):
Projectile.__init__(self, x, y, sizeX, sizeY, speed)
self.destX = 0 - self.sizeX
self.sprite = loadTile("bookProj.png", self.sizeX, self.sizeY)
def finished(self):
if self.x < self.destX:
return True
def move(self):
self.x -= self.speed
class SlimeProjectile(Projectile):
def __init__(self, x, y, sizeX, sizeY, speed):
Projectile.__init__(self, x, y, sizeX, sizeY, speed)
self.destY = 600
self.sprite = loadTile("slimeProj.png", self.sizeX, self.sizeY)
def finished(self):
if self.y == self.destY:
return True
return False
def move(self):
for i in range(self.speed):
if self.finished():
return
self.y += 1
class GridRestrictedObject():
def __init__(self, gridX, gridY):
self.gridX = gridX
self.gridY = gridY
class Character(GameObject):
def __init__(self, areaNumber, name, remainingHealth, maxHealth, speed, attack, direction):
GameObject.__init__(self, areaNumber)
self.name = name
self.remainingHealth = remainingHealth
self.maxHealth = maxHealth
self.speed = speed
self.attack = attack
self.direction = direction
def displayHealthBar(self, surface, topLeftX, topLeftY, length, unfilledColour, textColour):
percentageFilled = round(self.remainingHealth/self.maxHealth * length)
healthData = textFont.render(str(self.remainingHealth) + "/" + str(self.maxHealth), 1, textColour)
pygame.draw.rect(surface, unfilledColour, (topLeftX, topLeftY, length, 20), 0)
pygame.draw.rect(surface, RED, (topLeftX, topLeftY, percentageFilled, 20), 0)
pygame.draw.rect(surface, BLACK, (topLeftX, topLeftY, length, 20), 2)
surface.blit(healthData, (topLeftX + length + 10, topLeftY - 5))
class MovingCharacter(FreeMovingObject, Character):
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction):
FreeMovingObject.__init__(self, x, y)
Character.__init__(self, areaNumber, name, remainingHealth, maxHealth, speed, attack, direction)
def getGridPos(self, pointX, pointY, floored):
#Gets grid position from a position on the screen
gridPosX = (pointX - WIDTH/2 + GRID_WIDTH*SQUARE_SIZE/2)/SQUARE_SIZE
gridPosY = (pointY - GRID_DIST_TOP)/SQUARE_SIZE
if(floored):
return (floor(gridPosX + 1), floor(gridPosY + 1))
else:
return (gridPosX + 1, gridPosY + 1)
def slide(self, obstacleMap, mobs):
middle = self.getGridPos(self.x + SQUARE_SIZE/2, self.y + SQUARE_SIZE/2, True)
#Runs 3 times resulting in speed of 3
for i in range(3):
#Checks if character is still on ice
if obstacleMap[middle[1]][middle[0]] == "I":
newX = self.x + movement[self.direction][0]
newY = self.y + movement[self.direction][1]
#If no collision with mob or no collision with obstacles allows it to slide
for mob in mobs:
if mob != self:
if self.isContactEntity(mob, newX, newY):
return False
if self.isCollide(obstacleMap, newX, newY):
return False
else:
self.x = newX
self.y = newY
else:
return False
return True
def isCollide(self, obstacleMap, movedX, movedY):
cornerLocations = []
cornerLocations.append(self.getGridPos(movedX, movedY, False)) #Top left
cornerLocations.append(self.getGridPos(movedX + SQUARE_SIZE - 1, movedY, False)) #Top Right
cornerLocations.append(self.getGridPos(movedX, movedY + SQUARE_SIZE - 1, False)) #Bottom Left
cornerLocations.append(self.getGridPos(movedX + SQUARE_SIZE - 1, movedY + SQUARE_SIZE - 1, False)) #Bottom Right
#For all corner locations of a character, it checks if it is colliding with something
for corner in cornerLocations:
if not isInConstraint(corner[0], 0, GRID_WIDTH + 2) or not isInConstraint(corner[1], 0, GRID_HEIGHT + 2):
return True
elif obstacleMap[floor(corner[1])][floor(corner[0])] not in moveableSpaces:
return True
return False
def isContactEntity(self, entity, movedX, movedY):
newPos = self.getGridPos(movedX + SQUARE_SIZE/2, movedY + SQUARE_SIZE/2, False)
entityLocation = self.getGridPos(entity.x + SQUARE_SIZE/2, entity.y + SQUARE_SIZE/2, False)
if isInConstraint(newPos[0], entityLocation[0] - 1, entityLocation[0] + 1) and isInConstraint(newPos[1], entityLocation[1] - 1, entityLocation[1] + 1):
return True
else:
return False
class StaticCharacter(GridRestrictedObject, Character):
def __init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction):
GridRestrictedObject.__init__(self, gridX, gridY)
Character.__init__(self, areaNumber, name, remainingHealth, maxHealth, speed, attack, direction)
class Aggressive(MovingCharacter):
path = []
sprites = []
index = 1
pathAvailable = True
timeSinceLastSearch = 1
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level):
MovingCharacter.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction)
self.level = level
self.percentRun = self.level * 30
def draw(self):
display.blit(self.sprites[self.direction], (self.x, self.y))
def getPlayerPath(self, player, obstacleMap, mobs): #aStar algorithm
#If there was no path on last iteration it doesnt run for 50 calls to reduce lag
if(self.pathAvailable or self.timeSinceLastSearch % 50 == 0):
self.timeSinceLastSearch = 1
self.index = 1
#Initializes algorith
end = player.getGridPos(player.x, player.y, True)
start = player.getGridPos(self.x, self.y, True)
openSet = set()
openList = []
closedSet = set()
openList.append(Node(0, 0, 0, None, start))
openSet.add(start)
minf = 100000
toCheckIndex = 0
while len(openSet) > 0:
#Finds node with smallest f value
for i, node in enumerate(openList):
if node.f < minf:
minf = node.f
toCheckIndex = i
#Gets the current node
currentNode = openList.pop(toCheckIndex)
openSet.remove(currentNode.position)
closedSet.add(currentNode.position)
#Check if the node is the end and returns path if it is
if currentNode.position == end:
currentCheckNode = currentNode
path = []
while(currentCheckNode.parent != None):
path.insert(0, currentCheckNode.position)
currentCheckNode = currentCheckNode.parent
path.insert(0, start)
self.pathAvailable = True
self.path = path
return
#Gets squares from all four directions
for i in movement[1:]:
newPos = (currentNode.position[0] + i[0], currentNode.position[1] + i[1])
#Makes sure it is in the map and that it is not colliding with obstacle
if isInConstraint(newPos[0], 1, GRID_WIDTH) and isInConstraint(newPos[1], 1, GRID_HEIGHT):
if obstacleMap[newPos[1]][newPos[0]] in moveableSpaces:
#Makes sure node was not visited already
if newPos in closedSet or newPos in openSet:
continue
else:
#Generates nodes with heuristics and adds to open list
g = currentNode.g + 1
h = (currentNode.position[0] - newPos[0]) ** 2 + (currentNode.position[1] - newPos[1]) **2
f = g+h
openSet.add(newPos)
openList.append(Node(f, g, h, currentNode, newPos))
self.path = []
self.pathAvailable = False
else:
self.timeSinceLastSearch += 1
def moveToGridCoord(self, obstacleMap, gridX, gridY, mobs):
screenPos = getScreenPos(gridX, gridY)
#Finds which way mob needs to move
for i in range(self.speed):
if self.y < screenPos[1] and not self.isCollide(obstacleMap, self.x, self.y + 1):
self.direction = 3
elif self.x > screenPos[0] and not self.isCollide(obstacleMap, self.x - 1, self.y):
self.direction = 4
elif self.y > screenPos[1] and not self.isCollide(obstacleMap, self.x, self.y - 1):
self.direction = 1
elif self.x < screenPos[0] and not self.isCollide(obstacleMap, self.x + 1, self.y):
self.direction = 2
else:
return True
newX = self.x + movement[self.direction][0]
newY = self.y + movement[self.direction][1]
#Moves if no collision
if not self.isCollide(obstacleMap, newX, newY):
noEntityBlock = True
#Makes sure it is not colliding with another mob
for mob in mobs:
if mob != self:
if self.isContactEntity(mob, newX, newY):
noEntityBlock = False
if noEntityBlock:
self.x = newX
self.y = newY
return False
def moveToPlayer(self, player, obstacleMap, mobs):
playerPos = self.getGridPos(self.x, self.y, True)
if self.index < len(self.path):
if playerPos not in self.path:
return
if self.moveToGridCoord(obstacleMap, self.path[self.index][0], self.path[self.index][1], mobs):
if self.index < len(self.path) - 1:
self.index += 1
else:
self.getPlayerPath(player, obstacleMap, mobs)
class Zombie(Aggressive):
sprites = loadDirectionalSprites("zombie", "Zombie")
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level):
Aggressive.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level)
def loadProjectiles(self):
projectiles = []
projectiles.append(ZombieProjectile(randint(1400, 1500), 500, 250, 100, self.level + 2))
return projectiles
class Book(Aggressive):
sprites = loadDirectionalSprites("Book", "Book")
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level):
Aggressive.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level)
def loadProjectiles(self):
projectiles = []
for i in range(2 * self.level):
size = randint(45, 55)
projectiles.append(BookProjectile(randint(1400, 1600), randint(100, 550), size, size, self.level + randint(1, 5)))
return projectiles
class Slime(Aggressive):
sprites = loadDirectionalSprites("slime", "Slime")
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level):
Aggressive.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level)
def loadProjectiles(self):
projectiles = []
for i in range(2 * self.level):
size = randint(45, 55)
projectiles.append(SlimeProjectile(randint(300, 1050), randint(50, 100), size, size, self.level + randint(1, 3)))
return projectiles
class Necromancer(Aggressive):
sprites = loadDirectionalSprites("necromancer", "Necromancer")
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level):
Aggressive.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, level)
def loadProjectiles(self):
projectiles = []
attack = randint(1, 3)
#Loads one of the three attacks
if attack == 1:
for i in range(self.level):
size = randint(45, 65)
projectiles.append(SlimeProjectile(randint(300, 1050), randint(50, 100), size, size, self.level))
elif attack == 2:
for i in range(self.level):
size = randint(45, 65)
projectiles.append(BookProjectile(randint(1400, 1600), randint(100, 550), size, size, self.level))
else:
projectiles.append(ZombieProjectile(randint(1400, 1500), 500, 300, 125, self.level))
return projectiles
class Villager(StaticCharacter):
def __init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction, dialogue):
StaticCharacter.__init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction)
self.dialogue = dialogue
def speak(self):
drawTextBoxes(self.dialogue, 1000, BEIGE, self.name)
class SellingVillager(Villager):
def __init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction, dialogue, store):
Villager.__init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction, dialogue)
self.store = store
#Store interface
def sell(self, player):
selling = True
storeSurface = pygame.Surface((WIDTH, HEIGHT))
#Drawing the labels and store background
pygame.draw.rect(storeSurface, BEIGE, (400, 100, 600, 600), 0)
pygame.draw.rect(storeSurface, DARK_BEIGE, (400, 30, 600, 70), 0)
titleLabel = titleFont.render(self.name + "'s Store", 1, BLACK)
nameLabel = storeFont.render("NAME", 1, BLACK)
stockLabel = storeFont.render("STOCK", 1, BLACK)
costLabel = storeFont.render("PRICE", 1, BLACK)
storeSurface.blit(titleLabel, (450, 35))
storeSurface.blit(nameLabel, (450, 125))
storeSurface.blit(stockLabel, (650, 125))
storeSurface.blit(costLabel, (750, 125))
buttons = []
#Drawing the items
for i, storeItem in enumerate(self.store):
buttons.append(Button(850, 170 + i*50, 100, 25, FOREST_GREEN, "BUY", BLACK, OLIVE_GREEN))
itemName = storeFont.render(storeItem.item.name, 1, BLACK)
itemCost = storeFont.render(str(storeItem.cost), 1, BLACK)
storeSurface.blit(itemName, (450, 170 + i*50))
storeSurface.blit(itemCost, (750, 170 + i*50))
exitButton = Button(950, 30, 50, 50, RED, "X", BLACK, DARK_RED)
while(selling):
events = pygame.event.get()
checkIfExitGame(events)
display.blit(storeSurface, (0, 0))
#Displays amount of gold
amountOfGold = titleFont.render(str(player.goldAmount), 1, BLACK)
display.blit(loadTile("coin.png", 50, 50), (700, 635))
display.blit(amountOfGold, (760, 630))
#Rerenders stock since it will change
for i, storeItem in enumerate(self.store):
itemStock = storeFont.render(str(storeItem.stock), 1, BLACK)
display.blit(itemStock, (650, 170 + i*50))
exitButton.draw()
if exitButton.isLeftClicked(events):
selling = False
#Checks which item player is trying to purchase with buy button
for button in buttons:
button.draw()
for i, button in enumerate(buttons):
if button.isLeftClicked(events):
#Player purchases the item and has enough gold and space
if player.goldAmount >= self.store[i].cost and len(player.inventory) != player.maxInventorySize and self.store[i].stock > 0:
player.goldAmount -= self.store[i].cost
player.inventory.append(self.store[i].item)
self.store[i].stock -= 1
drawTextBoxes(["Thanks for buying!", "Here's your " + self.store[i].item.name], 500, BEIGE, self.name)
else:
drawTextBoxes(["I can't purchase this right now!"], 500, BEIGE, "(Thinking to yourself)")
pygame.display.update()
class GivingVillager(Villager):
def __init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction, dialogue, items):
Villager.__init__(self, areaNumber, gridX, gridY, name, remainingHealth, maxHealth, speed, attack, direction, dialogue)
self.items = items
def speak(self):
drawTextBoxes(self.dialogue, 1000, BEIGE, self.name)
def giveItem(self, player):
if(len(player.inventory) == player.maxInventorySize):
drawTextBoxes(["Throw out some items please"], 1000, BEIGE, self.name)
else:
if len(self.items) > 0:
for i in self.items:
player.inventory.append(i)
drawTextBoxes(["HERE IS A " + i.name + "!"], 1000, BEIGE, self.name)
self.items.clear()
class Player(MovingCharacter):
maxInventorySize = 16
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, goldAmount, inventory, activeWeapon, activeShield, addDamage):
MovingCharacter.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction)
self.goldAmount = goldAmount
self.inventory = inventory
self.activeWeapon = activeWeapon
self.activeShield = activeShield
self.addDamage = addDamage
def displayInventory(self, inBattle):
#Gets inventory background
inventorySurface = pygame.Surface((600, 600)).convert_alpha()
inventorySurface.fill(BEIGE)
allButtons = []
for i in range(4):
buttonRow = []
for k in range(4):
pygame.draw.rect(inventorySurface, DARK_BEIGE, (20 + i*155, 70 + k*130, 100, 100), 0)
buttonRow.append(Button(420 + k*155, 170 + i*130, 100, 100, BEIGE, "", BEIGE, BEIGE))
allButtons.append(buttonRow)
exitButton = Button(950, 100, 50, 50, RED, "X", BLACK, DARK_RED)
inInventory = True
while(inInventory):
events = pygame.event.get()
checkIfExitGame(events)
display.blit(inventorySurface, (400, 100))
exitButton.draw()
if exitButton.isLeftClicked(events):
inInventory = False
itemCounter = 0
for i in range(4):
for k in range(4):
if itemCounter < len(self.inventory):
item = self.inventory[itemCounter]
display.blit(pygame.transform.scale(item.sprite, (80, 80)), (430 + k*155, 170 + i*130))
itemCounter += 1
for i in range(4):
for k in range(4):
if i*4 + k < len(self.inventory):
if allButtons[i][k].isHovered():
currItem = self.inventory[i*4 + k]
itemName = textFont.render(currItem.name, 1, BLACK)
className = self.inventory[i*4 + k].__class__.__name__
if k < 2:
itemRect = itemName.get_rect(topleft = (430 + k*155, 170 + i*130))
else:
itemRect = itemName.get_rect(topright = (430 + k*155, 170 + i*130))
pygame.draw.rect(display, WHITE, itemRect, 0)
display.blit(itemName, itemRect)
pygame.draw.rect(display, GREY, (itemRect[0], itemRect[1] + itemRect[3], itemRect[2], 30))
if className == "Weapon" or className == "StrengthPotion":
stats = textFont.render("+" + str(currItem.effect) + " atk", 1, BLACK)
elif className == "Shield" or className == "HealthPotion":
stats = textFont.render("+" + str(currItem.effect) + " health", 1, BLACK)
display.blit(stats, (itemRect[0] + 5, itemRect[1] + itemRect[3] + 3))
if allButtons[i][k].isLeftClicked(events):
className = self.inventory[i*4 + k].__class__.__name__
usedItem = self.inventory[i*4 + k]
#Swaps weapons
if className == "Weapon":
if not inBattle:
self.inventory.pop(i*4 + k)
if self.activeWeapon != None:
self.inventory.append(self.activeWeapon)
self.activeWeapon = usedItem
#Swaps shields
elif className == "Shield":
if not inBattle:
self.inventory.pop(i*4 + k)
if self.activeShield != None:
self.maxHealth -= self.activeShield.effect
self.inventory.append(self.activeShield)
self.activeShield = usedItem
self.maxHealth += self.activeShield.effect
#Uses health potion if you can
elif className == "HealthPotion":
if self.remainingHealth != self.maxHealth:
self.inventory.pop(i*4 + k)
usedItem.usePot(self)
drawTextBoxes(["You gained " + str(usedItem.effect) + " health"], 500, BEIGE, "Mysterious voice")
if inBattle:
return
else:
drawTextBoxes(["I am already healthy", "I can not use this right now"], 500, BEIGE, "Thinking to yourself")
elif className == "StrengthPotion":
if inBattle:
drawTextBoxes(["You gained " + str(usedItem.effect) + " damage"], 500, BEIGE, "Mysterious voice")
return
else:
drawTextBoxes(["I can only use this in battle!"], 750, BEIGE, "Thinking to yourself")
elif allButtons[i][k].isRightClicked(events) and not inBattle:
if self.inventory[i*4 + k].throwable:
threwAway = self.inventory.pop(i*4 + k)
drawTextBoxes(["Threw away " + threwAway.name], 750, BEIGE, "Yourself")
else:
drawTextBoxes(["You should not throw this away!"], 750, BEIGE, "Voice in your head")
#Updates hotbar
pygame.draw.rect(display, BLACK, (150, 780, 1100, 105), 0)
if not inBattle:
self.loadHotBar()
self.drawHotBar(events, inBattle)
pygame.display.update()
class PlayerMap(Player):
hotBarSurface = None
inventoryButton = Button(830, 795, 100, 30, DARK_BEIGE, "Inventory", BLACK, WHITE)
canCut = False
canPush = False
sprites = loadDirectionalSprites("player", "Player")
def __init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, goldAmount, inventory, activeWeapon, activeShield, addDamage):
Player.__init__(self, areaNumber, x, y, name, remainingHealth, maxHealth, speed, attack, direction, goldAmount, inventory, activeWeapon, activeShield, addDamage)
def draw(self):
display.blit(self.sprites[self.direction], (self.x, self.y))
def getMovement(self, grid, mobs):
if not player.slide(currObstacleMap, mobs):
newX = self.x
newY = self.y
for i in range(self.speed):
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] or keys[pygame.K_LEFT] or keys[pygame.K_UP] or keys[pygame.K_DOWN]:
if keys[pygame.K_RIGHT]:
self.direction = 2
elif keys[pygame.K_LEFT]:
self.direction = 4
elif keys[pygame.K_UP]:
self.direction = 1
elif keys[pygame.K_DOWN]:
self.direction = 3
newX += movement[self.direction][0]
newY += movement[self.direction][1]
#Allows you to move if no collision
if not self.isCollide(grid, newX, newY):
self.x = newX
self.y = newY
def goNewArea(self): #Returns 0 if player has not left area, otherwise returns the direction they left from (clockwise starting from top)
cornerLocations = []
cornerLocations.append(self.getGridPos(self.x, self.y, False))
cornerLocations.append(self.getGridPos(self.x + SQUARE_SIZE, self.y + SQUARE_SIZE, False))
#Finds if you have left the area and returns which area you are leaving to
for i in range(2): #xPos
for k in range(2): #yPos
pointX = cornerLocations[i][0]
pointY = cornerLocations[k][1]
if(pointY <= 1):
return 1
elif(pointX >= GRID_WIDTH+1):
return 2
elif(pointY >= GRID_HEIGHT+1):
return 3
elif(pointX <= 1):
return 4
return 0
def getSpaceInfront(self): #Extra +- 1 removes issue of player being exactly right next to object due to nature of coordinate system
if self.direction == 1:
playerCoord = self.getGridPos(self.x + SQUARE_SIZE/2, self.y, True)
return (playerCoord[0], playerCoord[1] - 1)
elif self.direction == 2:
playerCoord = self.getGridPos(self.x + SQUARE_SIZE - 1, self.y + SQUARE_SIZE/2, True)
return (playerCoord[0] + 1, playerCoord[1])
elif self.direction == 3:
playerCoord = self.getGridPos(self.x + SQUARE_SIZE/2, self.y + SQUARE_SIZE - 1, True)
return (playerCoord[0], playerCoord[1] + 1)
elif self.direction == 4:
playerCoord = self.getGridPos(self.x, self.y + SQUARE_SIZE/2, True)
return (playerCoord[0] - 1, playerCoord[1])
def interactAndUpdate(self, currObstacleMap, signs, chests, givingVillagers, sellingVillagers): #Used to interact with environment and returns if map needs to be updated
spaceInfront = self.getSpaceInfront()
#Checks if space is in map
if isInConstraint(spaceInfront[0], 0, GRID_WIDTH + 2) and isInConstraint(spaceInfront[1], 0, GRID_HEIGHT + 2):
#If it is a sign
if currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "S":
for s in signs:
if s.areaNumber == self.areaNumber and s.gridX == spaceInfront[0] and s.gridY == spaceInfront[1]:
s.read(self)
return False
#If it is a chest
elif currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "C":
for c in chests:
if c.areaNumber == self.areaNumber and c.gridX == spaceInfront[0] and c.gridY == spaceInfront[1]:
c.giveItem(self)
return True
#If it is a cutting tree
elif currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "T":
if self.canCut:
currObstacleMap[spaceInfront[1]][spaceInfront[0]] = "."
else:
#Checks if player has acquired an axe and if they have allows them to cut trees
hasAxe = False
for item in self.inventory:
if item.name == "Axe":
hasAxe = True
if hasAxe:
self.canCut = True
currObstacleMap[spaceInfront[1]][spaceInfront[0]] = "."
return True
#if it is a moveable rock
elif currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "O":
movedX = spaceInfront[0] + movement[self.direction][0]
movedY = spaceInfront[1] + movement[self.direction][1]
if currObstacleMap[movedY][movedX] == ".":
currObstacleMap[movedY][movedX] = "O"
currObstacleMap[spaceInfront[1]][spaceInfront[0]] = "."
return True
#If it is a giving villager
elif currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "G":
for v in givingVillagers:
if v.areaNumber == self.areaNumber and v.gridX == spaceInfront[0] and v.gridY == spaceInfront[1]:
v.speak()
v.giveItem(self)
return False
#If it is a selling villager
elif currObstacleMap[spaceInfront[1]][spaceInfront[0]] == "$":
for v in sellingVillagers:
if v.areaNumber == self.areaNumber and v.gridX == spaceInfront[0] and v.gridY == spaceInfront[1]:
v.speak()
v.sell(self)
return True
def loadHotBar(self):
#Gets hotbar background
newHotBarSurface = pygame.Surface((500, 100))
newHotBarSurface.fill(BEIGE)
pygame.draw.rect(newHotBarSurface, DARK_BEIGE, (20, 10, 80, 80), 0)
pygame.draw.rect(newHotBarSurface, DARK_BEIGE, (120, 10, 80, 80), 0)
#Displays active weapons
if self.activeWeapon != None:
newHotBarSurface.blit(pygame.transform.scale(self.activeWeapon.sprite, (70, 70)), (25, 15))
elif self.activeShield != None:
newHotBarSurface.blit(pygame.transform.scale(self.activeShield.sprite, (70, 70)), (125, 15))
#Displays gold amount
goldText = textFont.render(str(self.goldAmount), 1, BLACK)
goldCoin = loadTile("coin.png", 25, 25)
newHotBarSurface.blit(goldCoin, (220, 15))
newHotBarSurface.blit(goldText, (250, 10))
#Displays health bar
self.displayHealthBar(newHotBarSurface, 220, 60, 150, WHITE, BLACK)
self.hotBarSurface = newHotBarSurface
def drawHotBar(self, events, inBattle):
display.blit(self.hotBarSurface, (450, 785))
self.inventoryButton.draw()
if self.inventoryButton.isLeftClicked(events):
self.displayInventory(inBattle)
#Player battle container is not completley related to the player
class PlayerBattle(Player):
jumpCounter = 0
gravityCounter = 0
sprite = loadTile("heart.png", 50, 50)
def __init__(self, playerMap):
self.areaNumber = None
self.x = 700
self.y = 550
self.direction = None
self.goldAmount = playerMap.goldAmount
self.speed = playerMap.speed - 2
self.attack = playerMap.attack
self.remainingHealth = playerMap.remainingHealth
self.maxHealth = playerMap.maxHealth
self.inventory = playerMap.inventory
self.activeWeapon = playerMap.activeWeapon
self.activeShield = playerMap.activeShield
self.addDamage = playerMap.addDamage
def getMovement(self, gravity):
newX = self.x
newY = self.y
for i in range(self.speed):
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
newX += 1
elif keys[pygame.K_LEFT]:
newX -= 1
if not gravity:
if keys[pygame.K_UP]:
newY -= 1
if keys[pygame.K_DOWN]:
newY += 1
if newY >= 100 and newY <= 550:
self.y = newY
if newX >= 300 and newX <= 1050:
self.x = newX
if gravity:
#If the character should still be rising
if self.jumpCounter < 50 and self.jumpCounter != 0:
self.y -= 4
self.jumpCounter += 1
#If character has reached peak
elif self.jumpCounter == 50:
self.jumpCounter = 0
#If character tries to jump
if keys[pygame.K_UP] and self.y == 550:
self.jumpCounter = 1
#If character is in mid air
if self.y != 550:
newY = self.y
for i in range(round(self.gravityCounter**2/7500)):
newY += 1
if newY == 550:
self.gravityCounter = 0
break
self.y = newY
if newY != 550:
self.gravityCounter += 1
def draw(self):
display.blit(self.sprite, (self.x, self.y))
#Environmental obstacles