-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1677 lines (1457 loc) · 63 KB
/
app.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 random
from collections import defaultdict
import math
import sys
import os
import pygame
import mapgen
import itertools
import time
import abc
import webbrowser
size = width, height = 1280, 720
black = 0, 0, 0
white = 255, 255, 255
fps = 0
ticked = 0
winstyle = 0
fullscreen = False
player = None
dialog = None
debug_mode = len(sys.argv) > 1 and sys.argv[1] == "--debug"
if debug_mode:
print("/!\ Debug mode enabled")
pygame.init()
SCREENRECT = pygame.Rect(0, 0, width, height)
bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle | pygame.DOUBLEBUF, 32)
screen = pygame.display.set_mode(
SCREENRECT.size, winstyle | pygame.DOUBLEBUF, bestdepth
)
pygame.display.set_caption("ChadRogue")
hit_sound = pygame.mixer.Sound("assets/hitted.ogg")
app_icon = pygame.image.load(os.path.join("assets", "icon.png"))
pygame.display.set_icon(app_icon)
clock = pygame.time.Clock()
plane = pygame.Surface((size), pygame.SRCALPHA)
camera_size = 20
camera_x, camera_y = 0, 0
dpi = width / camera_size
already_drawn = []
def loadify(path, size=0, keep_ratio=False, keep_size=False):
global dpi
good_path = os.path.join("assets", path)
image = pygame.image.load(good_path).convert_alpha()
if keep_size:
return image
ratio = image.get_width() / image.get_height() if keep_ratio else 1
if keep_size:
return image
return pygame.transform.scale(image, ((dpi + size) * ratio, dpi + size))
def sign(x):
if x == 0:
return 0
elif x > 0:
return 1
elif x < 0:
return -1
def inverse_direction(direction):
return (-direction[0], -direction[1])
def get_angle(x1,x2,y1,y2):
dx = x1-x2
dy = y1-y2
return((math.atan2( -dy,dx) * 180 /math.pi)-90)
def rotate_image(image, angle):
rotated_image = pygame.transform.rotate(image, angle)
return rotated_image
def translated_rect(rect):
global camera_x, camera_y
return pygame.Rect(rect.x - camera_x, rect.y - camera_y, rect.width, rect.height)
def fill_open(x, y, grid):
if x == 0:
Wall((-1 * dpi, y * dpi))
elif x == len(grid[0]):
Wall((len(grid[0]) * dpi, y * dpi))
elif y == 0:
Wall((x * dpi, -1 * dpi))
elif y == len(grid):
Wall((x * dpi, len(grid) * dpi))
def check_adjacent(x, y, grid):
for dx, dy in itertools.product((-1, 0, 1), (-1, 0, 1)):
if (
(dx == 0 and dy == 0)
or (x == 0 and dx == -1)
or (y == 0 and dy == -1)
or (x == len(grid[0]) - 1 and dx == 1)
or (y == len(grid) - 1 and dy == 1)
):
continue
if grid[y + dy][x + dx] != ".":
return True
return False
def get_player_pos_grid():
center = player.origin_rect.center
return (math.floor(center[0] / dpi), math.floor(center[1] / dpi))
def get_creature_pos_grid(creature):
center = creature.origin_rect.center
return (math.floor(center[0] / dpi), math.floor(center[1] / dpi))
def move_player_to_spawn():
global camera_x, camera_y, player
spawn_point = game_logic.current_map.rooms[0].center
camera_x = spawn_point.x * dpi - width / 2 + player.origin_rect.width // 2
camera_y = spawn_point.y * dpi - height / 2 + player.origin_rect.height // 2
(player.origin_rect.x, player.origin_rect.y) = (spawn_point.x * dpi, spawn_point.y * dpi)
def update_map_near_player():
player_grid_pos = get_player_pos_grid()
coords = propagate(mapgen.Coord(player_grid_pos[0], player_grid_pos[1]), map_grid)
for c in coords:
x, y = c
elem = game_logic.current_map.get_character_at(c)
if elem in ("%", "#", "x", "S","w","L","P", "T", "€"):
if (x, y) not in already_drawn:
g = Ground((x * dpi, y * dpi), trapped=(elem == "T"))
if elem == "S":
Stairs((x * dpi, y * dpi))
elif elem == "€":
Treasure(game_logic.current_map.treasure.item, (x * dpi, y * dpi))
elif elem == "T":
traps_group.add(g)
already_drawn.append((x, y))
elif elem == ".":
if (x, y) not in already_drawn:
Wall((x * dpi, y * dpi))
already_drawn.append((x, y))
for creature in creature_group.sprites():
if get_creature_pos_grid(creature) in already_drawn:
all_sprites.add(creature)
all_sprites.add(creature.health_bar)
else:
all_sprites.remove(creature)
all_sprites.remove(creature.health_bar)
for item in inventoryobject_group.sprites():
if get_creature_pos_grid(item) in already_drawn:
all_sprites.add(item)
else:
all_sprites.remove(item)
def draw_map():
global map_grid
for s in mapdependent_group.sprites():
s.kill()
mapdependent_group.clear(screen, SCREENRECT)
mapdependent_group.empty()
map_grid = game_logic.current_map.grid()
already_drawn.clear()
for y, row in enumerate(map_grid):
for x, elem in enumerate(row):
if elem == "x":
for abstract_creature in game_logic.current_map.creatures:
if abstract_creature.position == mapgen.Coord(x, y):
c = Creature(
(x * dpi, y * dpi),
abstract_creature.id,
abstract_creature.speed,
abstract_creature.flying,
abstract_creature.hp,
key = abstract_creature.has_key,
strength = abstract_creature.strength,
ranged= abstract_creature.ranged,
cooldown=abstract_creature.cool,
id=abstract_creature.idd
)
c.health_bar = CreatureHealthBar()
c.health_bar.creature = c
elif elem == "w":
for abstract_weapon in game_logic.current_map.weapons:
if abstract_weapon.position == mapgen.Coord(x, y):
Weapon(
(x * dpi, y * dpi),
id=abstract_weapon.id,
subid=abstract_weapon.sub_id,
durability=abstract_weapon.durability,
damage=abstract_weapon.damage,
reach=abstract_weapon.reach,
attack_cooldown=abstract_weapon.attack_cooldown
)
elif elem == "L":
for abstract_spell in game_logic.current_map.spells:
if abstract_spell.position == mapgen.Coord(x,y):
Spell(
(x*dpi,y*dpi),
id=abstract_spell.id,
subid=abstract_spell.sub_id,
damage=abstract_spell.damage,
radius=abstract_spell.radius,
speed=abstract_spell.speed,
attack_cooldown=abstract_spell.attack_cooldown
)
elif elem == "P":
for abstract_potion in game_logic.current_map.potions:
if abstract_potion.position == mapgen.Coord(x,y):
Potion(
(x * dpi, y * dpi),
id = abstract_potion.id
)
def get_adjacent_case(x,y,grid):
if x > 0 and x < len(grid[0]) and y > 0 and y < len(grid):
res = []
res.append(mapgen.Coord(x+1,y))
res.append(mapgen.Coord(x-1,y))
res.append(mapgen.Coord(x,y+1))
res.append( mapgen.Coord(x,y-1))
return res
def is_case_goodenough(coo,grid):
case = grid[coo.y][coo.x]
if case in ["#", "%","S","x","w","L","P", "€","T"]:
return True
return False
def propagate(start,grid, max_recursive_depth = 5 ):
visible = []
to_iter = [start]
to_iter_next = []
current_recursion = []
already_itered = []
for i in range(max_recursive_depth):
for j in to_iter:
current_recursion = get_adjacent_case(j.x,j.y,grid)
for k in current_recursion :
if k not in visible :
visible.append(k)
if is_case_goodenough(k,grid) and k not in already_itered:
to_iter_next.append(k)
current_recursion.clear()
already_itered.extend(to_iter_next)
to_iter.clear()
to_iter = to_iter_next.copy()
to_iter_next.clear()
return visible
def get_neighbours(position):
x, y = position
return [
(x+1, y),
(x-1, y),
(x, y+1),
(x, y-1)
]
def bfs(creature, grid):
start = get_creature_pos_grid(creature)
goal = get_player_pos_grid()
queue = [start]
visited = [start]
parents = defaultdict(lambda: None)
while len(queue) != 0:
current = queue.pop(0)
if current == goal:
path = []
while current:
path.insert(0, current)
current = parents[current]
return path
neighbours = get_neighbours(current)
for n in neighbours:
if is_case_goodenough(mapgen.Coord(n[0], n[1]), grid) and n not in visited:
visited.append(n)
parents[n] = current
queue.append(n)
class Mask(pygame.sprite.Sprite):
def __init__(self):
super().__init__(self.containers)
self.image = loadify("mask.png", keep_ratio=True, keep_size=True)
self.rect = self.image.get_rect()
(self.rect.x, self.rect.y) = (0, 0)
class Animation:
def __init__(self, spritelist, rate):
self.spritelist = spritelist
self.rate = rate
self.frame_index = 0
self.curr_sprite = 0
def update_animation(self,frame):
if frame % self.rate == 0:
self.curr_sprite += 1
if self.curr_sprite >= len(self.spritelist):
self.curr_sprite = 0
return self.spritelist[self.curr_sprite]
def rotate_animation(self,frame):
if frame % self.rate == 0:
print('roted')
img = rotate_image(self.spritelist[self.curr_sprite],45)
return img
else : return self.spritelist[self.curr_sprite]
class FPSCounter(pygame.sprite.Sprite):
def __init__(self):
super().__init__(self.containers)
self.font = pygame.font.Font("assets/Retro_Gaming.ttf", 20)
self.color = "white"
self.update()
self.rect = self.image.get_rect().move(0, 0)
def update(self):
self.image = self.font.render(f"FPS: {round(fps)}", False, self.color)
class Dialog(pygame.sprite.Sprite):
def __init__(self):
super().__init__(self.containers)
self.font = pygame.font.Font("assets/Retro_Gaming.ttf", 20)
self.color = "red"
self.message = ""
self.update()
self.origin_rect = self.image.get_rect().move(width / 2, 0)
@property
def rect(self):
return translated_rect(self.origin_rect)
def move(self, coord):
(self.origin_rect.x, self.origin_rect.y) = coord
def update(self):
self.image = self.font.render(self.message, False, self.color)
class Wall(pygame.sprite.Sprite):
def __init__(self, initial_position=None):
super().__init__(self.containers)
self.origin_rect = self.image.get_rect()
if initial_position is None:
initial_position = (0, 0)
(self.origin_rect.x, self.origin_rect.y) = initial_position
@property
def rect(self):
return translated_rect(self.origin_rect)
def draw(self, screen):
screen.blit(self.image, translated_rect(self.origin_rect))
class Background(pygame.sprite.Sprite):
def __init__(self):
super().__init__(self.containers)
self.rect = self.image.get_rect(center=SCREENRECT.center)
def move(self, direction, delta_time):
direction = tuple([round(0.05 * delta_time * c) for c in direction])
self.rect.move_ip(inverse_direction(direction))
def draw(self, screen):
screen.blit(self.image, translated_rect(self.rect))
class Ground(pygame.sprite.Sprite):
def __init__(self, initial_position=None, trapped=False):
super().__init__(self.containers)
if trapped:
self.image = loadify("magma.png",0,True)
else :
self.image = random.choice(random.choices(self.images, [1, 50, 1, 1, 1, 1]))
self.origin_rect = self.image.get_rect()
self.trapped = trapped
if initial_position is None:
initial_position = (0, 0)
(self.origin_rect.x, self.origin_rect.y) = initial_position
@property
def rect(self):
return translated_rect(self.origin_rect)
def draw(self, screen):
screen.blit(self.image, translated_rect(self.origin_rect))
class Stairs(pygame.sprite.Sprite):
def __init__(self, initial_position=None):
super().__init__(self.containers)
self.origin_rect = self.image.get_rect()
if initial_position is None:
initial_position = (0, 0)
(self.origin_rect.x, self.origin_rect.y) = initial_position
@property
def rect(self):
return translated_rect(self.origin_rect)
class Treasure(pygame.sprite.Sprite):
def __init__(self, item, initial_position=None):
super().__init__(self.containers)
self.origin_rect = self.image.get_rect()
if initial_position is None:
initial_position = (0, 0)
(self.origin_rect.x, self.origin_rect.y) = initial_position
self.item = item
@property
def rect(self):
return translated_rect(self.origin_rect)
class Projectile(pygame.sprite.Sprite):
def __init__(self,position,sprites,speed,direction,dmg,particle = None,ff = False):
super().__init__(self.containers)
self.ff = ff
self.speed = speed
self.direction = direction
self.dmg = dmg
angle = math.atan2(self.direction[0],self.direction[1])
angle = angle * (180/math.pi)
rot_sprites = []
for i in sprites :
rot_sprites.append(rotate_image(i,angle+180+45))
self.sprites = rot_sprites
self.anim = Animation(self.sprites,2)
self.image = self.anim.update_animation(0)
self.origin_rect = self.image.get_rect()
self.origin_rect.center = position
if particle != None :
self.has_particles = True
self.particle_sys = ParticleEffect(100,200,None,[0,0.1],translated_rect(self.origin_rect),color = (255,200,0))
else :
self.has_particles = False
self.frame_index = 0
@property
def rect(self):
return translated_rect(self.origin_rect)
def update(self):
if self.has_particles :
self.particle_sys.spawner = self.rect
self.particle_sys.update(ticked)
self.frame_index+=1
self.image = self.anim.update_animation(self.frame_index)
self.move(self.direction,ticked)
if self.ff :
if pygame.sprite.collide_mask(self,player) :
player.take_damage(self.dmg)
self.kill()
colliding_creatures = pygame.sprite.spritecollide(self,creature_group,False)
if not self.ff :
if len(colliding_creatures) != 0 :
colliding_creatures[0].health -= self.dmg
self.kill()
colliding_walls = []
for i in obstacle_group.sprites():
if i.origin_rect.collidepoint(self.origin_rect.center):
colliding_walls.append(i)
if len(colliding_walls) != 0 :
self.kill()
if mapgen.Coord(player.origin_rect.center[0],player.origin_rect.center[1]).distance(mapgen.Coord(self.origin_rect.center[0],self.origin_rect.center[1])) > 20*dpi :
self.kill()
def move(self,direction,delta_time):
direction = tuple([round(self.speed * delta_time * c) for c in direction])
self.origin_rect.move_ip(direction[0],direction[1])
class InventoryObject(pygame.sprite.Sprite,metaclass=abc.ABCMeta):
def __init__(self, initial_position):
super().__init__(self.containers)
self.picked_up = False
self.image = self.images[0]
self.origin_rect = self.image.get_rect()
(self.origin_rect.x, self.origin_rect.y) = initial_position
def __bool__(self):
return True
@property
def rect(self):
return self.origin_rect if self in player_inv_group.sprites() else translated_rect(self.origin_rect)
def move(self, direction, delta_time):
direction = tuple([round(delta_time * c) for c in direction])
self.rect.move_ip(inverse_direction(direction))
def update(self):
if pygame.sprite.collide_rect(player, self):
offset = player.inventory.first_empty_slot()
if player.take(self):
self.kill()
self.image = self.images[1]
self.origin_rect = self.image.get_rect(center = inv_slot_group.sprites()[offset].rect.center)
player_inv_group.add(self)
@abc.abstractmethod
def use(self):
pass
class Weapon(InventoryObject):
def __init__(self, initial_position, id, subid, durability, damage, reach, attack_cooldown):
self.id = id
self.durability = durability
self.attack_cooldown = attack_cooldown
self.subid = subid
self.damage = (damage * (game_logic.active_level + 1 ))
self.reach = reach * dpi
self.images = []
if self.id == "sword":
self.description = "Slash your enemies!"
if subid == "diamond_sword" :
self.images.append(loadify("diamond_sword.png", 0, True))
self.images.append(loadify("diamond_sword.png", -25, True))
elif subid == "emerald_sword" :
self.images.append(loadify("emerald_sword.png", 0, True))
self.images.append(loadify("emerald_sword.png", -25, True))
elif subid == "amber_sword" :
self.images.append(loadify("amber_sword.png", 0, True))
self.images.append(loadify("amber_sword.png", -25, True))
else:
self.images.append(loadify("sword.png", 0, True))
self.images.append(loadify("sword.png", -25, True))
if self.id == "bow":
self.images.append(loadify("bow.png", -10, True))
self.images.append(loadify("bow.png", -25, True))
self.description = "Pew pew!"
self.last_attack = 0
super().__init__(initial_position)
def use(self):
if not (time.time() - self.last_attack > self.attack_cooldown):
return
player.is_striking = True
if self.id == "sword":
pos = pygame.mouse.get_pos()
cos45 = 1 / math.sqrt(2)
mouse_cos = (pos[0] - player.rect.center[0]) / math.sqrt((pos[0] - player.rect.center[0])**2 + (pos[1] - player.rect.center[1])**2)
for creature in creature_group.sprites():
distance = math.sqrt((creature.rect.center[0] - player.rect.center[0])**2 + (creature.rect.center[1] - player.rect.center[1])**2)
cos = (creature.rect.center[0] - player.rect.center[0]) / distance
if (
(cos > cos45 and mouse_cos > cos45)
or (cos < -cos45 and mouse_cos < -cos45)
or (creature.rect.center[1] > player.rect.center[1] and pos[1] > player.rect.center[1])
or (creature.rect.center[1] <= player.rect.center[1] and pos[1] <= player.rect.center[1])
) and distance <= self.reach:
creature.health -= self.damage
self.durability -= 1
if self.id == "bow":
mouse_pos = pygame.math.Vector2(pygame.mouse.get_pos())
player_pos = pygame.math.Vector2(player.rect.center)
direction = (mouse_pos - player_pos).normalize()
Projectile(player.origin_rect.center,[loadify("arrow.png",-35,True)],1,direction, self.damage)
self.last_attack = time.time()
def update(self):
if self.durability <= 0:
player.inventory.remove(self)
self.kill()
super().update()
class Key(InventoryObject):
def __init__(self, initial_position):
self.images = []
self.images.append(loadify("key.png", 5, True))
self.images.append(loadify("key.png", -25, True))
self.description = "Use it on a chest!"
super().__init__(initial_position)
def use(self):
player.inventory.remove(self)
self.kill()
class Potion(InventoryObject):
def __init__(self, initial_position, id):
self.images = []
self.id = id
if self.id == "healing":
self.images.append(loadify("potion_heal.png", -20, True))
self.images.append(loadify("potion_heal.png", -30, True))
self.description = "Gives you 2 HP!"
elif self.id == "resting":
self.images.append(loadify("potion_rest.png", -20, True))
self.images.append(loadify("potion_rest.png", -30, True))
self.description = "Can't move for a bit"
elif self.id == "mana":
self.images.append(loadify("potion_mana.png", -20, True))
self.images.append(loadify("potion_mana.png", -30, True))
self.description = "+30% of your magic points!"
elif self.id == "armor":
self.images.append(loadify("armor.png", -20 , True))
self.images.append(loadify("armor.png", -30 , True))
self.description = "Upgrade your armor!"
super().__init__(initial_position)
def use(self):
if self.id == "healing":
player.health += 2
elif self.id == "mana":
player.magic_points += 0.3 * player.max_mp
elif self.id == "resting":
player.is_resting = True
player.health += 5
player.magic_points += 0.2 * player.max_mp
elif self.id == "armor":
if player.armor < 50:
player.armor += 5
# does not work yet because creatures aren't updated when not in fog or idk
player.inventory.remove(self)
self.kill()
class Spell(InventoryObject):
def __init__(self, initial_position, id, subid, damage, radius, speed, attack_cooldown):
self.id = id
self.subid = subid
if damage :
self.damage = (damage * (game_logic.active_level + 1 ))
else :
self.damage = 0
self.radius = radius
self.speed = speed
self.attack_cooldown = attack_cooldown
self.images = []
if self.id == "fireball" :
self.images.append(loadify("fireball_spell.png",-10,True))
self.images.append(loadify("fireball_spell.png",-25,True))
self.description = "Burn your enemies!"
self.mp_usage = 5
if self.id == "lightning":
self.images.append(loadify("lightning_spell.png",-10,True))
self.images.append(loadify("lightning_spell.png",-25,True))
self.description = "220V in your enemies!"
self.mp_usage = 7
if self.id == "teleportation":
self.images.append(loadify("teleportation_spell.png",-10,True))
self.images.append(loadify("teleportation_spell.png",-25,True))
self.description = "Woosh!"
self.mp_usage = 15
if self.id == "ice":
self.images.append(loadify("ice_spell.png",0,True))
self.images.append(loadify("ice_spell.png",-25,True))
self.description = "Freeze your enemies"
self.mp_usage = 10
self.last_attack = 0
super().__init__(initial_position)
def use(self):
if not (time.time() - self.last_attack > self.attack_cooldown):
return
if not (player.magic_points >= self.mp_usage):
return
if self.id == "fireball":
mouse_pos = pygame.math.Vector2(pygame.mouse.get_pos())
player_pos = pygame.math.Vector2(player.rect.center)
direction = (mouse_pos - player_pos).normalize()
Projectile(player.origin_rect.center,[loadify("fireball.png",-25,True)],1,direction, self.damage,particle=1)
self.last_attack = time.time()
player.magic_points -= self.mp_usage
if self.id == "lightning":
mouse_pos = pygame.math.Vector2(pygame.mouse.get_pos())
player_pos = pygame.math.Vector2(player.rect.center)
direction = (mouse_pos - player_pos).normalize()
angle = math.atan2(direction[0],direction[1])
angle = (angle*180)/math.pi
LightingBolt(player,[pygame.transform.rotate(loadify("lightning.png",100,True),angle),pygame.transform.rotate(loadify("lightning2.png",100,True),angle)],angle,0.2,20)
self.last_attack = time.time()
player.magic_points -= self.mp_usage
if self.id == "teleportation":
mouse_pos = pygame.mouse.get_pos()
distance = math.sqrt((mouse_pos[0] - player.rect.center[0])**2 + (mouse_pos[1] - player.rect.center[1])**2)
if distance <= self.radius and any([i.rect.collidepoint(mouse_pos) for i in floor_group.sprites()]):
player.move((mouse_pos[0] - player.rect.center[0],mouse_pos[1] - player.rect.center[1]), 1, with_speed = False)
self.last_attack = time.time()
player.magic_points -= self.mp_usage
if self.id == "ice" :
mobs = []
for i in creature_group.sprites():
if math.sqrt((player.origin_rect.center[0]-i.origin_rect.center[0])**2+(player.origin_rect.center[1]-i.origin_rect.center[1])**2) <= self.radius*dpi:
mobs.append(i)
Frozen(player.origin_rect.center,mobs,5)
self.last_attack = time.time()
player.magic_points -= self.mp_usage
class Frozen(pygame.sprite.Sprite):
def __init__(self,position, mobs, dur):
super().__init__(self.containers)
self.mobs = mobs
self.dur = dur
self.time = time.time()
self.image = loadify("ice_spell_alpha.png",200,True)
self.origin_rect = self.image.get_rect(center=position)
self.speeds = []
for i in mobs:
self.speeds.append(i.speed)
i.speed = 0
@property
def rect(self):
return translated_rect(self.origin_rect)
def update(self):
if time.time() < self.time + self.dur:
plane.blit(self.image,translated_rect(self.origin_rect))
else :
for i in range(len(self.mobs)):
self.mobs[i].speed = self.speeds[i]
self.kill()
del self
class LightingBolt(pygame.sprite.Sprite):
def __init__(self,cast,images,angle,dmg,lifetime = 30,ff = False):
self.angle = angle
self.frame = 0
self.ff = ff
self.cast = cast
self.dmg = dmg
self.lifetime = lifetime
self.anim = Animation(images,5)
self.image = self.anim.update_animation(0)
self.rect = self.image.get_rect()
self.rect.x = cast.rect.center[0]
self.rect.y = cast.rect.center[1]
self.adjust()
super().__init__(self.containers)
def update(self):
self.adjust()
self.frame += 1
self.image = self.anim.update_animation(self.frame)
if self.frame == self.lifetime:
self.kill()
if not self.ff:
for i in creature_group.sprites():
if pygame.sprite.collide_mask(i,self):
i.health -= self.dmg
if self.ff:
if pygame.sprite.collide_mask(self,player):
player.take_damage(self.dmg)
def adjust(self):
cast = self.cast
angle = self.angle
if angle < 90 and angle >0 :
self.rect.x = cast.rect.center[0]
self.rect.y = cast.rect.center[1]
if angle< 0 and angle > -90 :
self.rect.x = cast.rect.center[0]- self.rect.width
self.rect.y = cast.rect.center[1]
if angle < -90 and angle > -180 :
self.rect.x = cast.rect.center[0]- self.rect.width
self.rect.y = cast.rect.center[1] - self.rect.height
if angle >90 :
self.rect.x = cast.rect.center[0]
self.rect.y = cast.rect.center[1] - self.rect.height
class Player(pygame.sprite.Sprite):
speed = 0.35
inventory_size = 8
flipped = False
def __init__(self, initial_position=None):
super().__init__(self.containers)
self.images = [loadify(i, size=-10) for i in self.assets]
self.currimage = 0
self.armor = 0
self.armor_text = Text(self.armor, (69, 69, 69), (381, height - 32), size = 30, centered = True)
self.image = self.images[self.currimage]
self.max_health = 8
self.health = self.max_health
self.origin_rect = self.image.get_rect(center=SCREENRECT.center)
self.last_trapped = 0
if initial_position is not None:
(self.origin_rect.x, self.origin_rect.y) = initial_position
self.inventory = Inventory([None for i in range(Player.inventory_size)])
self.level = 1
self.xp = 0
self.xp_cap = 20
self.max_mp = 50
self.magic_points = self.max_mp
self.is_striking = False
self.time_striking = 0
self.is_resting = False
self.resting_time = 0
def take_damage(self, amount):
damageMultiplier = ((100-self.armor)/100)
player.health -= amount * damageMultiplier
hit_sound.play()
def move(self, direction, delta_time, with_speed = True):
global camera_x, camera_y
origin_direction = direction
direction = tuple([round(self.speed * delta_time * c) if with_speed else round(delta_time * c) for c in direction])
camera_x += direction[0]
camera_y += direction[1]
self.origin_rect.move_ip(direction)
background_sprite.move(origin_direction, delta_time)
dialog.message = ""
for stair_object in pygame.sprite.spritecollide(self, stairs_group, False):
dialog.message = "Press E to go up"
dialog.move((stair_object.origin_rect.x, stair_object.origin_rect.y - 0.5 * dpi))
for treasure_object in pygame.sprite.spritecollide(self, treasures_group, False):
if isinstance(self.inventory.picked_item,Key):
item = treasure_object.item
if isinstance(treasure_object.item,mapgen.Weapon):
Weapon(treasure_object.origin_rect[:2],item.id, subid=item.sub_id, durability=item.durability, damage=item.damage, reach=item.reach, attack_cooldown=item.attack_cooldown)
elif isinstance(treasure_object.item,mapgen.Spell):
Spell(treasure_object.origin_rect[:2],treasure_object.item.id, subid=item.sub_id, damage=item.damage, radius=item.radius, speed=item.speed, attack_cooldown=item.attack_cooldown)
all_sprites.remove(treasure_object)
treasures_group.remove(treasure_object)
self.inventory.picked_item.use()
if any(pygame.sprite.spritecollide(self, traps_group, False)):
if time.time() - self.last_trapped > 5:
self.take_damage(1)
self.last_trapped = time.time()
if any(pygame.sprite.spritecollide(self, obstacle_group, False)):
camera_x -= direction[0]
camera_y -= direction[1]
self.origin_rect.move_ip(inverse_direction(direction))
background_sprite.move(inverse_direction(origin_direction), delta_time)
@property
def rect(self):
return translated_rect(self.origin_rect)
def draw(self, screen):
screen.blit(self.image, translated_rect(self.origin_rect))
def update(self):
if any(list(i.picked_up for i in self.inventory if i is not None)):
if self.is_striking:
self.currimage = 2
else:
self.currimage = 1
else:
self.currimage = 0
self.image = self.images[self.currimage] if not Player.flipped else pygame.transform.flip(self.images[self.currimage], True, False)
if self.is_striking:
self.time_striking += 1
if self.time_striking >= 10:
self.is_striking = False
self.time_striking = 0
if self.is_resting:
self.resting_time += 1
if self.resting_time >= 100:
self.is_resting = False
self.resting_time = 0
if self.xp >= self.xp_cap:
self.level += 1
self.xp = self.xp % self.xp_cap
self.xp_cap *= 1.2
if self.level%5 == 0:
self.max_health += 2
self.max_mp += 20
self.health = self.max_health
self.magic_points = self.max_mp
if self.health > self.max_health:
self.health = self.max_health
if self.magic_points < 0:
self.magic_points = 0
elif self.magic_points > self.max_mp:
self.magic_points = self.max_mp
self.armor_text.kill()
self.armor_text = Text(self.armor, (69, 69, 69), (381, height - 32), size = 30, centered = True)
def take(self,thing):
if isinstance(thing,InventoryObject):
return self.inventory.add(thing)
raise TypeError("Not an item")
def drop(self):
self.inventory.drop((self.rect.x + camera_x,self.rect.y + camera_y + dpi))
class Text(pygame.sprite.Sprite):
def __init__(self, text, color, position, size = 15, centered = False):
super().__init__(self.containers)
self.text = str(text)
self.color = color
self.font = pygame.font.Font("assets/Retro_Gaming.ttf", size)
self.image = self.font.render(self.text, False, self.color)
self.rect = self.image.get_rect(topleft = position) if not centered else self.image.get_rect(center = position)
class StatsBg(pygame.sprite.Sprite):
def __init__(self, position):
super().__init__(self.containers)
self.image = loadify("parchemin.png",200,True)
self.rect = self.image.get_rect(topleft = position)
class StatsGui:
def __init__(self,item):
self.attributes = []
self.texts = {}
self.bg = StatsBg((width - 5*dpi,height - 4*dpi))
self.update(item)
def update(self, item):
self.kill()
if item:
self.texts["name"] = str(type(item)).split('.')[1][:-2]
self.texts["description"] = item.description
if isinstance(item,Weapon) or isinstance(item,Spell):
self.texts["damage"] = item.damage
if isinstance(item,Weapon):
self.texts["durability"] = item.durability
else:
self.texts["radius"] = item.radius
starting_height = 9 * height / 12
for i in range(len(self.texts)):
tupel = list(self.texts.items())[i]
i *= 2
self.attributes.append(Text(tupel[0]+" :", (0,0,0), (width - 4.5 * dpi, starting_height + (i * dpi) / 3)))
self.attributes.append(Text(tupel[1], (0,0,0), (width - 4.5 * dpi, starting_height + ((1+i) * dpi) / 3)))
self.bg = StatsBg((width - 5*dpi,height - 4*dpi))
def kill(self):
for i in self.attributes:
i.kill()
del i
self.attributes = []
self.texts = {}
self.bg.kill()
class InvSlot(pygame.sprite.Sprite):
def __init__(self, offset, total_nb):
super().__init__(self.containers)
self.has_picked_item = False
self.image = loadify("slot.png", size=-20)
center_p = (width / 2,height)
self.rect = self.image.get_rect(center = center_p)
self.rect.move_ip(self.rect[2]*(offset - total_nb//2),-self.rect[3]/2)
if total_nb%2 == 0:
self.rect.move_ip(self.rect[2]/2,0)
def update(self):
self.image = loadify("selected_slot.png", size=-20) if self.has_picked_item else loadify("slot.png", size=-20)
class Inventory:
def __init__(self,items):
self.items = items
self.size = len(self.items)
for i in range(self.size):
InvSlot(i, self.size)
self.gui = StatsGui(self.picked_item)
def __repr__(self):
return str(self.items)
def __getitem__(self,key):
return self.items[key]
def __setitem__(self,key,value):
self.items[key] = value
def has_empty_slot(self):
return None in self.items
def first_empty_slot(self):
return min(list(i for i in range(len(self.items)) if self[i] is None)) if self.has_empty_slot() else None
def add(self,thing):
if self.has_empty_slot():
self[self.first_empty_slot()] = thing
return True
return False
def remove(self,thing):