-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2218 lines (1770 loc) · 80 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
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 copy
import math
import random
import CasesGraphiques as CG
import pygame
# random.seed(234789)
def _find_getch():
"""Single char input, only works only on mac/linux/windows OS terminals"""
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt (Windows') getch.
import msvcrt
return lambda: msvcrt.getch().decode('utf-8')
# POSIX system. Create and return a getch that manipulates the tty.
import sys
import tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return _getch
def sign(x: int) -> int:
if x > 0:
return 1
return -1
def opp(x: int) -> int:
return -x + 1
def clear_list(list_to_clear: list) -> None:
for i in range(len(list_to_clear)):
for j in range(len(list_to_clear)):
list_to_clear[i][j] = None
class Coord(object):
"""Implementation of a map coordinate"""
def __init__(self, x: int, y: int) -> None:
"""
Is a coordinate of the map
:param x: x coordinate
:param y: y coordinate
"""
self.x = x
self.y = y
def __eq__(self, other: "Coord") -> bool:
return self.x == other.x and self.y == other.y
def __repr__(self) -> str:
return f"<{str(self.x)},{str(self.y)}>"
def __add__(self, other: "Coord") -> "Coord":
return Coord(self.x + other.x, self.y + other.y)
def __sub__(self, other: "Coord") -> "Coord":
return Coord(self.x - other.x, self.y - other.y)
def distance(self, other: "Coord") -> float:
"""Returns the distance between two coordinates."""
d = self - other
return math.sqrt(d.x * d.x + d.y * d.y)
def empty_around(self, actual_map: "Map") -> bool:
# Return True if the coordinates around are corresponding
res = True
for y in range(-1, 2):
for x in range(-1, 2):
res = res and (actual_map.get(self + Coord(x, y)) == Map.ground or actual_map.get(
self + Coord(x, y)) == actual_map.hero)
return res
def get_empty_coord_around(self, actual_map: "Map") -> "Coord":
available_coord_list = []
o = actual_map.get(self)
for i in range(-1, 2):
for j in range(-1, 2):
way = Coord(i, j)
if actual_map.check_move(o, way) == Map.ground:
available_coord_list.append(self + way)
return random.choice(available_coord_list)
def get_tuple(self) -> tuple:
return self.x, self.y
class Element(object):
"""Base class for game elements. Have a name.
Abstract class."""
def __init__(self, name: str, abbreviation: str = "") -> None:
self.name = name
if abbreviation == "":
abbreviation = name[0]
self.abbreviation = abbreviation
self.graphicOutput = None
def __repr__(self) -> str:
return self.abbreviation
def description(self) -> str:
"""Description of the element"""
return f"<{self.name}>"
def meet(self, hero: "Hero") -> None:
"""Makes the hero meet an element. Not implemented. """
raise NotImplementedError('Abstract Element')
class RoomObject(Element):
def __init__(self, name: str = "", abbreviation: str = "", usage: "function" = None) -> None:
Element.__init__(self, name, abbreviation)
self.usage = usage
self.graphicOutput = []
for i in range(2):
try:
self.graphicOutput.append(CG.get_room_object_image(self.name + '-' + str(i)))
except FileNotFoundError:
print("Not image for:", self.name + '-' + str(i))
pass
def meet(self, hero: "Hero") -> bool:
"""The roomObject is encountered by hero.
The hero uses the roomObject.
Return True if used."""
if not isinstance(hero, Hero):
return False
return self.usage()
@staticmethod
def go_upstair() -> bool:
g = the_game()
if g.actual_floor + 1 < len(g.floor_list):
g.floor.rm(g.floor.pos(g.hero))
g.actual_floor += 1
g.floor = g.gv.floor = g.floor_list[g.actual_floor]
g.add_message('You are now in stage ' + str(g.actual_floor + 1) + '/' + str(len(g.floor_list)))
stair_coord = g.floor.pos(g._room_objects['downstair'])
new_coord = stair_coord.get_empty_coord_around(g.floor)
g.floor.put(new_coord, g.hero)
g.hero.x = new_coord.x
g.hero.y = new_coord.y
return True
return False
@staticmethod
def go_downstair() -> bool:
g = the_game()
if g.actual_floor - 1 >= 0:
g.floor.rm(g.floor.pos(g.hero))
g.actual_floor -= 1
g.floor = g.gv.floor = g.floor_list[g.actual_floor]
g.add_message('You are now in stage ' + str(g.actual_floor + 1) + '/' + str(len(g.floor_list)))
stair_coord = g.floor.pos(g._room_objects['upstair'])
new_coord = stair_coord.get_empty_coord_around(g.floor)
g.floor.put(new_coord, g.hero)
g.hero.x = new_coord.x
g.hero.y = new_coord.y
return True
return False
@staticmethod
def meet_trader() -> None:
list_of_items_sold = []
for i in range(2):
list_of_items_sold.append(
the_game().rand_element(Game.equipments, the_game().floor_list[the_game().actual_floor].floor_number))
list_of_items_sold.append(
the_game().rand_element(Game.weapons, the_game().floor_list[the_game().actual_floor].floor_number))
the_game().gv.draw_trader(list_of_items_sold)
class Creature(Element):
"""A creature that occupies the dungeon.
Is an Element. Has hit points and strength."""
default_inventory_size = 10
def __init__(self, name: str, hp: int, abbreviation: str = "", strength: int = 1, xp: int = 0,
weapon_slot: list = None, powers_list: list = None, cooldown: int = 0) -> None:
super().__init__(name, abbreviation)
self.hp = hp
self.default_hp = hp
self.strength = strength
self.xp = xp
if weapon_slot is not None:
self.weapon_slot = weapon_slot
else:
self.weapon_slot = []
if powers_list is not None:
self.powers_list = powers_list
else:
self.powers_list = []
self.cooldown = 0
self._default_cooldown = cooldown
self._inventory = []
# Graphics
self.graphicOutput = CG.get_monster_image(self.name)
def description(self) -> str:
"""Description of the creature"""
if self.hp > 0:
return Element.description(self) + "(" + str(self.hp) + ")"
return Element.description(self) + "(0)"
def gain_xp(self, xp_point):
raise NotImplementedError
def gain_level(self, nb_of_level):
raise NotImplementedError
def meet(self, other: "Creature") -> bool:
"""The creature is encountered by an other creature.
The other one hits the creature. Return True if the creature is dead."""
self.hit(other)
the_game().add_message("The " + other.name + " hits the " + self.description())
if self.hp > 0:
return False
if isinstance(self, Creature) and not isinstance(self, Hero):
other.gain_xp(self.xp)
return True
def hit(self, other: "Creature") -> None:
if len(other.powers_list) != 0:
for effect_infos_list in other.powers_list:
if other.cooldown == 0: # The cooldown ended
effect_infos_list[0].add_effect(
effect_infos_list[0](self, effect_infos_list[1], effect_infos_list[2]))
other.cooldown = other._default_cooldown
else:
other.cooldown -= 1
if other.has_weapon():
self.hp -= other.current_weapon().damage
else:
self.hp -= other.strength
def equip_weapon(self, weapon: "Weapon") -> None:
if len(self.weapon_slot) != 0:
self._inventory.append(self.weapon_slot[0])
self.weapon_slot.clear()
self.weapon_slot.append(weapon)
self._inventory.remove(weapon)
the_game().add_message(f"You equipped {weapon.name}")
def remove_current_weapon(self) -> None:
if self.current_weapon():
if len(self._inventory) < self.default_inventory_size:
self._inventory.append(self.current_weapon())
self.weapon_slot.clear()
the_game().add_message("You removed your weapon from it's slot")
else:
the_game().add_message("You don't have any space in your inventory to place your weapon")
else:
the_game().add_message("You currently don't have a weapon to remove from it's slot")
def has_weapon(self) -> bool:
if len(self.weapon_slot) >= 1:
return True
def current_weapon(self) -> bool or "Weapon":
if self.has_weapon():
return self.weapon_slot[0]
else:
return False
class Hero(Creature):
"""The hero of the game.
Is a creature. Has an inventory of elements. """
default_inventory_size = 10
default_stomach_size = 10
default_level_size = 25
default_hp = 10
def __init__(self, name="Hero", hp=default_hp, abbreviation="@", strength=2, level=1, xp=24, gold=0,
stomach=default_stomach_size,
weapon_slot=None):
Creature.__init__(self, name, hp, abbreviation, strength, xp, weapon_slot)
self.xp = xp
self.level_step = Hero.default_level_size
self.level = level
self.gold = gold
self.stomach = stomach
self.default_stomach_size = stomach
# GRAPHICS
images = CG.get_hero_image("Template")
self.graphicOutput = images[0]
self.animationUDLR = {(0, -1): images[12:16], # cannot put Coord since it's not hashable
(0, 1): images[:4],
(-1, 1): images[:4],
(1, 1): images[:4],
(-1, 0): images[4:8],
(-1, -1): images[4:8],
(1, 0): images[8:12],
(1, -1): images[8:12],
}
self.state = 0
self.moving_UDLR = [False, False, False, False]
self.x = 0
self.y = 0
def description(self):
"""Description of the hero"""
if len(self.weapon_slot) != 0:
return Creature.description(self) + " |" + str(self.current_weapon()) + "|"
else:
return Creature.description(self)
def full_description(self):
"""Complete description of the hero"""
res = ''
for e in self.__dict__:
if e[0] != ' ' and "default" not in e:
if e == "xp":
res += '> ' + e + ' : ' + str(self.__dict__[e]) + "/" + str(
self.default_level_size * self.level) + '\n'
else:
res += '> ' + e + ' : ' + str(self.__dict__[e]) + '\n'
res += '> INVENTORY : ' + str([x.name for x in self._inventory]) + '\n'
res += '> Effects : ' + str(
[f"{x.name}<{x.level}>({x.duration})" for x in the_game().active_effects if x.creature is self])
if self.has_weapon():
res += '> Weapon : ' + str(self.current_weapon().name)
return res
@staticmethod
def check_equipment(o):
"""Check if o is an Equipment."""
if not isinstance(o, Equipment):
raise TypeError('Not a Equipment')
def take(self, elem):
"""The hero takes adds the equipment to its inventory"""
self.check_equipment(elem)
if elem.name == "gold":
self.gold += 1
else:
if len(self._inventory) + 1 <= self.default_inventory_size:
self._inventory.append(elem)
elif len(self._inventory) > Hero.default_inventory_size:
the_game().add_message("You don't have enough space in your inventory")
def check_inventory_size(self):
if len(self._inventory) > Hero.default_inventory_size:
the_game().add_message("Inventory full. Delete an item to gain space")
return False
return True
def use(self, elem):
"""Use a piece of equipment"""
if elem is None:
return
self.check_equipment(elem)
if elem not in self._inventory:
raise ValueError('Equipment ' + elem.name + 'not in inventory')
if elem.use(self):
self._inventory.remove(elem)
def delete_item(self, elem, throwing=False):
"""Delete an element from the inventory"""
if len(self._inventory) >= 0:
if elem in self._inventory:
self._inventory.remove(elem)
if throwing:
the_game().add_message(f"You have successfully thrown the item : {elem.name}")
else:
the_game().add_message(f"You have successfully deleted the item : {elem.name}")
elif elem in self.weapon_slot:
self.weapon_slot.remove(elem)
if throwing:
the_game().add_message(f"You have successfully thrown the item : {elem.name}")
else:
the_game().add_message(f"You have successfully deleted the item : {elem.name}")
else:
the_game().add_message("Could not find the item to delete. Maybe try with another value")
def gain_xp(self, creature_xp):
self.xp += creature_xp
the_game().add_message("You gained {0} XP points".format(creature_xp))
xp_to_use = self.xp
self.level_step = self.default_level_size * self.level
level_won = 0
if xp_to_use > self.level_step:
while xp_to_use > self.level_step:
xp_to_use -= self.level_step
self.gain_level(1)
self.level_step = self.default_level_size * self.level
level_won += 1
self.xp = xp_to_use
the_game().add_message("You won {0} level(s) and are now level {1}".format(level_won, self.level))
def gain_level(self, nb_of_level):
self.level += 1
self.strength += nb_of_level
self.gold += nb_of_level + self.level
the_game().add_message(
"You now have a strength of {0} and won {1} gold coins".format(self.strength, self.level))
def check_stomach(self):
cool_down_value = 5
if self.stomach == 0:
if not hasattr(Hero.check_stomach, "cool_down"):
setattr(Hero.check_stomach, "cool_down", cool_down_value)
else:
if Hero.check_stomach.cool_down == 0:
self.hp -= 1
Hero.check_stomach.cool_down = cool_down_value - 1
the_game().add_message("WARNING : No more food !")
else:
Hero.check_stomach.cool_down -= 1
def buy(self, o):
if isinstance(o, Equipment):
if self.check_inventory_size():
if self.gold >= o.price:
self.gold -= o.price
self.take(o)
the_game().add_message(f'You bought {o.name} for {o.price} gold')
else:
the_game().add_message(f'Not enough gold. {o.price - self.gold} more gold needed')
@staticmethod
def choose_direction():
the_game().add_message("Choose a direction to orientate yourself using the keys to move")
the_game().gv.draw_message(200)
pygame.display.update()
choice = None
while choice is None:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if the_game().gv.qwerty:
if event.key == pygame.K_w:
choice = "z"
elif event.key == pygame.K_a:
choice = "q"
elif event.key == pygame.K_s or event.key == pygame.K_x:
choice = "x"
elif event.key == pygame.K_d:
choice = "d"
elif event.key == pygame.K_q:
choice = "a"
elif event.key == pygame.K_e:
choice = "e"
elif event.key == pygame.K_z:
choice = "w"
elif event.key == pygame.K_c:
choice = "c"
else:
if event.key == pygame.K_z:
choice = "z"
elif event.key == pygame.K_q:
choice = "q"
elif event.key == pygame.K_s or event.key == pygame.K_x:
choice = "x"
elif event.key == pygame.K_d:
choice = "d"
elif event.key == pygame.K_a:
choice = "a"
elif event.key == pygame.K_e:
choice = "e"
elif event.key == pygame.K_w:
choice = "w"
elif event.key == pygame.K_c:
choice = "c"
if choice is not None:
the_game().gv.inventory_on = False
return Map.dir[choice]
def throw_item(self, item, distance):
if not isinstance(item, Equipment):
return False
hero_coord = the_game().floor.pos(self)
direction = Hero.choose_direction()
if not direction:
return False
item_coord = hero_coord + direction
for i in range(distance):
if i == 0:
things_on_next_cell = the_game().floor.get(the_game().floor.pos(self) + direction)
else:
things_on_next_cell = the_game().floor.get(the_game().floor.pos(item) + direction)
if isinstance(things_on_next_cell, Creature):
hit = False
# Verify that the item is a weapon
if isinstance(item, Weapon):
things_on_next_cell.hp -= item.launching_damage
hit = True
if things_on_next_cell.hp <= 0:
self.gain_xp(creature_xp=things_on_next_cell.xp)
the_game().floor.rm(the_game().floor.pos(things_on_next_cell))
the_game().add_message(f"[{things_on_next_cell.name}] has been killed using {item.name}")
# If this item is not a weapon, use the item on the creature encountered
else:
item.use(things_on_next_cell, monster=True)
# If it is not the first throw, the item has been placed on the map and needs to be removed
if i != 0:
the_game().floor.rm(the_game().floor.pos(item))
# The item is removed from the inventory only if he doesn't come back
if not item.come_back:
self.delete_item(item, True)
# If a creature has been hit it appears in the game chat
if hit:
the_game().add_message(f"[{things_on_next_cell.name}] lost {item.launching_damage} hp")
break
# Verify that the item encounter an equipment
elif isinstance(things_on_next_cell, Equipment) or isinstance(things_on_next_cell, RoomObject):
# If it is the first movement of the throw it can't be placed
if i == 0:
the_game().add_message("You can't throw the item in this direction")
else:
# The item is removed from the inventory only if he doesn't come back
if not item.come_back:
self.delete_item(item, True)
# The item is removed from the map if he comes back
else:
the_game().floor.rm(the_game().floor.pos(item))
the_game().add_message(f"The {item.name} came back to it's owner")
break
# Verify that the item encounter something different from the floor
elif things_on_next_cell != the_game().floor.ground:
if i == 0:
the_game().add_message("You can't throw the item in this direction")
else:
# The item is removed from the inventory only if he doesn't come back
if not item.come_back:
self.delete_item(item, True)
# The item is removed from the map is he comes back
else:
the_game().floor.rm(the_game().floor.pos(item))
the_game().add_message(f"The {item.name} came back to it's owner")
break
# Verify that the item encounters a floor cell
elif things_on_next_cell == the_game().floor.ground:
# If it is the first movement, just place the item
if i == 0:
the_game().floor.put(item_coord, item)
# If the item reach the max distance...
elif i == distance - 1:
# ... and can come back, delete it from the map, add text in game chat
if item.come_back:
the_game().floor.rm(the_game().floor.pos(item))
the_game().add_message(f"The {item.name} came back to it's owner")
# ... and can't come back, delete it from the inventory
else:
self.delete_item(item, True)
# If the item can continue, move it in it's direction
else:
the_game().floor.move(item, direction)
else:
raise NotImplementedError("Error might be due to an object not being managed.")
class Effect(object):
def __init__(self, creature):
self.game = the_game()
self.creature = creature
self.value = 0
self.info = ""
self.duration = None
self.level = 0
image = CG.get_image('Effects/' + self.name + '.png') # change
self.graphicOutput = pygame.transform.scale(image, (32, 32))
def delete(self):
try:
self.game.active_effects.remove(self)
del self
except ValueError:
pass
def update(self):
if isinstance(self, EphemeralEffect):
self.action()
if self.duration is not None:
self.duration -= 1
if self.duration <= 0:
self.deactivate()
return True
def action(self):
self.game.add_message(self.info)
def add_effect(self):
self.game.active_effects.append(self)
def activate(self) -> None:
self.action()
if self not in self.game.active_effects:
self.add_effect()
def deactivate(self):
self.game.add_message(self.info)
self.delete()
@staticmethod
def clear(unique=True):
effects_to_delete = []
for effect in the_game().active_effects:
if effect.creature is the_game().hero:
effects_to_delete.append(effect)
for effect in effects_to_delete:
Effect.delete(effect)
return unique
class EphemeralEffect(Effect):
def __init__(self, creature, duration, level):
super().__init__(creature)
self.duration = duration
self.level = level
def activate(self, unique: bool = True) -> bool:
super().activate()
if self.duration is not None:
self.duration -= 1
if self.duration <= 0:
self.deactivate()
return unique
def deactivate(self, kill: bool = False) -> None:
if kill:
self.info = f"[{self.creature.name}] has been killed by {self.name}<{self.level}>"
else:
self.info = f"[{self.creature.name}] {self.name} effect disappeared"
super().deactivate()
class HealEffect(EphemeralEffect):
LEVEL_FACTOR = 1
DESCRIPTION = "Recovering hp : +"
def __init__(self, creature, duration, level):
self.name = "Heal"
super().__init__(creature, duration, level)
self.value = self.level * HealEffect.LEVEL_FACTOR
def action(self):
if self.creature.default_hp > self.creature.hp + self.value:
self.creature.hp += self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {HealEffect.DESCRIPTION}{self.value}"
else:
self.creature.hp = self.creature.default_hp
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | Full Health : {self.creature.hp}/{self.creature.hp}"
super().action()
class PoisonEffect(EphemeralEffect):
LEVEL_FACTOR = 1
DESCRIPTION = "Losing hp : -"
def __init__(self, creature, duration, level):
self.name = "Poison"
super().__init__(creature, duration, level)
self.value = self.level * PoisonEffect.LEVEL_FACTOR
def action(self):
self.creature.hp -= self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {PoisonEffect.DESCRIPTION}{self.value}"
if self.creature.hp == 0:
the_game().floor.rm(the_game().floor.pos(self.creature))
super().deactivate(True)
else:
super().action()
class FeedEffect(EphemeralEffect):
"""
Effect used to feed the hero. Creatures don't have a stomach so they can't be applied this effect.
"""
LEVEL_FACTOR = 1
DESCRIPTION = "I'm eating : +"
def __init__(self, creature, duration, level):
if isinstance(creature, Hero):
self.name = "Feed"
super().__init__(creature, duration, level)
self.value = self.level * FeedEffect.LEVEL_FACTOR
def action(self) -> None:
if self.creature.default_stomach_size > self.creature.stomach + self.value:
self.creature.stomach += self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {FeedEffect.DESCRIPTION}{self.value}"
else:
self.creature.stomach = self.creature.default_stomach_size
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | Max food : {self.creature.stomach}/{self.creature.stomach}"
super().action()
class HungerEffect(EphemeralEffect):
LEVEL_FACTOR = 1
DESCRIPTION = "I'm hungry : -"
def __init__(self, creature, duration, level):
if isinstance(creature, Hero):
self.name = "Hunger"
super().__init__(creature, duration, level)
self.value = self.level * HungerEffect.LEVEL_FACTOR
def action(self):
if isinstance(self.creature, Hero):
self.creature.stomach -= self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {HungerEffect.DESCRIPTION}{self.value}"
super().action()
class TeleportEffect(EphemeralEffect): # IS AN INSTANT EFFECT
DESCRIPTION = "You have been teleported"
def __init__(self, creature, duration=1):
self.name = "Teleportation"
super().__init__(creature, duration, 0)
def action(self):
"""Teleport the creature"""
r = the_game().floor.rand_room()
c = r.rand_coord()
while not the_game().floor.get(c) == Map.ground:
c = r.rand_coord()
the_game().floor.rm(the_game().floor.pos(self.creature))
the_game().floor.put(c, self.creature)
self.info = f"The creature <{self.creature.name}> has been teleported"
# CONSTANT EFFECTS
class ConstantEffect(Effect):
def __init__(self, creature):
super().__init__(creature)
self.has_been_activated = False
def activate(self, unique=True):
if not self.has_been_activated:
super().activate()
self.has_been_activated = True
return unique
def deactivate(self):
self.info += f" [{self.creature.name}] {self.name} effect disappeared"
super().deactivate()
class StrengthEffect(ConstantEffect):
LEVEL_FACTOR = 1
DESCRIPTION_ACTIVATE = "I feel stronger : +"
DESCRIPTION_DEACTIVATE = "<End of boost> I feel weaker : -"
def __init__(self, creature, duration=None, level=1):
self.name = "Strength"
super().__init__(creature)
self.duration = duration
self.level = level
self.value = self.level * StrengthEffect.LEVEL_FACTOR
def action(self):
self.creature.strength += self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {StrengthEffect.DESCRIPTION_ACTIVATE}{self.value}"
super().action()
def activate(self, unique=True):
if not self.has_been_activated:
super().activate(unique)
super().update()
return unique
def deactivate(self):
self.creature.strength -= self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {StrengthEffect.DESCRIPTION_DEACTIVATE}{self.value}"
super().deactivate()
class WeaknessEffect(ConstantEffect):
LEVEL_FACTOR = 1
DESCRIPTION_ACTIVATE = "I feel weaker : -"
DESCRIPTION_DEACTIVATE = "<End of malus> I feel stronger : +"
def __init__(self, creature, duration=None, level=1):
self.name = "Weakness"
super().__init__(creature)
self.duration = duration
self.level = level
self.value = self.level * WeaknessEffect.LEVEL_FACTOR
def action(self):
self.creature.strength -= self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {WeaknessEffect.DESCRIPTION_ACTIVATE}{self.value}"
super().action()
def activate(self, unique=True):
if not self.has_been_activated:
super().activate(unique)
super().update()
return unique
def deactivate(self):
self.creature.strength += self.value
self.info = f"[{self.creature.name}] | {self.name}<{self.level}> | {WeaknessEffect.DESCRIPTION_DEACTIVATE}{self.value}"
super().deactivate()
# EQUIPMENT
class Equipment(Element):
"""A piece of equipment"""
def __init__(self, name, abbreviation="", usage=None, durability=None, price=1):
Element.__init__(self, name, abbreviation)
self.usage = usage
self.durability = durability
self.price = price
self.come_back = False
# GRAPHICS
image = CG.get_item_image(self.name)
self.graphicOutput = [pygame.transform.scale(image, (16, 16)), pygame.transform.scale(image, (32, 32))]
def meet(self, hero):
"""Makes the hero meet an element. The hero takes the element."""
hero.take(self)
the_game().add_message("You pick up a " + self.name)
return True
def use(self, creature, monster=False):
"""Uses the piece of equipment. Has effect on the hero according usage.
Return True if the object is consumed."""
if self.usage is None:
if not monster:
the_game().add_message(f"The {creature.name} can't use the item {self.name}")
return False
else:
the_game().add_message(f"The {creature.name} uses the item {self.name}")
try:
return self.usage(self, creature)
except AttributeError:
pass
class Weapon(Equipment):
"""A weapon which can be used by the Hero or the monsters"""
def __init__(self, name, abbreviation="", price=1, damage=1, launching_damage=1, come_back=False):
Equipment.__init__(self, name, abbreviation, price)
self.damage = damage
self.launching_damage = launching_damage
self.come_back = come_back # The weapon can come back to the hero when used (like a boomerang)
class Room(object):
"""A rectangular room in the map"""
def __init__(self, c1, c2, special_objects=None):
self.c1 = c1
self.c2 = c2
if special_objects is None:
special_objects = []
self.specialObjects = special_objects
def __repr__(self):
return "[" + str(self.c1) + ", " + str(self.c2) + "]"
def __contains__(self, coord):
return self.c1.x <= coord.x <= self.c2.x and self.c1.y <= coord.y <= self.c2.y
def intersect(self, other):
"""Test if the room has an intersection with another room"""
sc3 = Coord(self.c2.x, self.c1.y)
sc4 = Coord(self.c1.x, self.c2.y)
return self.c1 in other or self.c2 in other or sc3 in other or sc4 in other or other.c1 in self
def center(self):
"""Returns the coordinates of the room center"""
return Coord((self.c1.x + self.c2.x) // 2, (self.c1.y + self.c2.y) // 2)
def rand_coord(self):
"""A random coordinate inside the room"""
return Coord(random.randint(self.c1.x, self.c2.x), random.randint(self.c1.y, self.c2.y))
def rand_empty_coord(self, map):
"""A random coordinate inside the room which is free on the map."""
c = self.rand_coord()
while map.get(c) != Map.ground or c == self.center():
c = self.rand_coord()
return c
def rand_empty_middle_coord(self, map):
"""Same as rand_empty_coord but surrounded by ground"""
list_of_coord_available = []
for y in range(self.c1.y + 1, self.c2.y):
for x in range(self.c1.x + 1, self.c2.x):
c = Coord(x, y)
if c.empty_around(map) and c != self.center():
list_of_coord_available.append(c)
if len(list_of_coord_available) == 0:
return self.rand_coord()
else:
return random.choice(list_of_coord_available)
def decorate(self, map):
"""Decorates the room by adding a random equipment and monster."""
for elem in self.specialObjects:
map.put(self.rand_empty_middle_coord(map), elem)