-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1829 lines (1372 loc) · 57.6 KB
/
main.py
File metadata and controls
1829 lines (1372 loc) · 57.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Following the Python Roguelike Tutorial by Terrible Programmer
# using PyGame and libtcod
# YouTube for The Terrible Programmer: https://www.youtube.com/channel/UCYpYQNHs2NN-J-UC7Pn4G5A
import string
import pygame
import random
import math
import pickle
import gzip
import datetime
import os
from typing import Tuple, Type, Any
# Libraries
import tcod as libtcod
# Game files
import constants
# Type checking
PosXY = Tuple[int, int]
#
# STRUCTURES
#
class str_Tile:
def __init__(self, block_path: bool) -> None:
self.block_path = block_path
self.seen = False
class str_Preferences:
def __init__(self):
self.vol_sound = .5
self.vol_music = .5
#
# OBJECTS
#
class obj_Assets:
def __init__(self) -> None:
self.load_sprites()
self.load_audio()
self.sound_adjust()
def load_sprites(self):
# Sprites
self.reptiles = obj_Spritesheet('data/reptiles.png')
self.aquatic = obj_Spritesheet('data/aquatic_creatures.png')
self.wall = obj_Spritesheet('data/Wall.png')
self.floor = obj_Spritesheet('data/Floor.png')
self.shield = obj_Spritesheet('data/Shield.png')
self.medwep = obj_Spritesheet('data/MedWep.png')
self.scroll = obj_Spritesheet('data/Scroll.png')
self.flesh = obj_Spritesheet('data/Flesh.png')
self.tile = obj_Spritesheet('data/Tile.png')
self.rodents = obj_Spritesheet('data/Rodents.png')
self.light = obj_Spritesheet('data/Light.png')
self.doors = obj_Spritesheet('data/Door0.png')
self.A_PLAYER = self.reptiles.get_Animation(2, 'm', 5, 16, 16, (32, 32))
self.A_SNAKE_01 = self.reptiles.get_Animation(2, 'e', 5, 16, 16, (32, 32))
self.A_SNAKE_02 = self.reptiles.get_Animation(2, 'i', 5, 16, 16, (32, 32))
self.A_SNAKE_03 = self.reptiles.get_Animation(2, 'k', 5, 16, 16, (32, 32))
self.A_ENEMY = self.aquatic.get_Animation(2, 'k', 1, 16, 16, (32, 32))
self.A_MOUSE = self.rodents.get_Animation(2, 'a', 2, 16, 16, (32, 32))
self.S_CORPSE = self.flesh.get_Sprite(3, 0, 16, 16, (32, 32))
self.S_CORPSE_HP = self.flesh.get_Sprite(1, 1, 16, 16, (32, 32))
self.S_SWORD = self.medwep.get_Sprite(0, 0, 16, 16, (32, 32))
self.S_SHIELD = self.shield.get_Sprite(0, 0, 16, 16, (32, 32))
self.S_SCROLL_01 = self.scroll.get_Sprite(0, 0, 16, 16, (32, 32))
self.S_SCROLL_02 = self.scroll.get_Sprite(0, 1, 16, 16, (32, 32))
self.S_SCROLL_03 = self.scroll.get_Sprite(1, 4, 16, 16, (32, 32))
self.S_LAMP = self.light.get_Sprite(4, 0, 16, 16, (32, 32))
self.S_WALL = self.wall.get_Sprite(3, 3, 16, 16, (32, 32))[0]
self.S_WALL_UNSEEN = self.wall.get_Sprite(3, 12, 16, 16, (32, 32))[0]
self.S_FLOOR = self.floor.get_Sprite(1, 4, 16, 16, (32, 32))[0]
self.S_FLOOR_UNSEEN = self.floor.get_Sprite(1, 10, 16, 16, (32, 32))[0]
self.S_STAIRS_DOWN = self.tile.get_Sprite(5, 1, 16, 16, (32, 32))
self.S_STAIRS_UP = self.tile.get_Sprite(4, 1, 16, 16, (32, 32))
self.S_PORTAL_CLOSED = self.doors.get_Sprite(2, 5, 16, 16, (32, 32))
self.S_PORTAL_OPEN = self.doors.get_Sprite(3, 5, 16, 16, (32, 32))
self.MAIN_MENU_BG = pygame.transform.scale(pygame.image.load('data/main_menu_image.jpg'),
(constants.CAMERA_WIDTH, constants.CAMERA_HEIGHT))
self.animation_dict = {
"A_PLAYER": self.A_PLAYER,
"A_SNAKE_01": self.A_SNAKE_01,
"A_SNAKE_02": self.A_SNAKE_02,
"A_SNAKE_03": self.A_SNAKE_03,
"A_ENEMY": self.A_ENEMY,
"A_MOUSE": self.A_MOUSE,
"S_CORPSE": self.S_CORPSE,
"S_CORPSE_HP": self.S_CORPSE_HP,
"S_SWORD": self.S_SWORD,
"S_SHIELD": self.S_SHIELD,
"S_SCROLL_01": self.S_SCROLL_01,
"S_SCROLL_02": self.S_SCROLL_02,
"S_SCROLL_03": self.S_SCROLL_03,
"S_STAIRS_DOWN": self.S_STAIRS_DOWN,
"S_STAIRS_UP": self.S_STAIRS_UP,
"S_LAMP": self.S_LAMP,
"S_PORTAL_CLOSED": self.S_PORTAL_CLOSED,
"S_PORTAL_OPEN": self.S_PORTAL_OPEN
}
def load_audio(self):
self.snd_master_list = []
self.background_music = "data/IntroMusic.wav"
self.snd_hit1 = self.add_sound("data/Hit_Hurt3.wav")
self.snd_hit2 = self.add_sound("data/Hit_Hurt4.wav")
self.snd_hard1 = self.add_sound("data/Hit_Hard1.wav")
self.snd_hard2 = self.add_sound("data/Hit_Hard2.wav")
self.snd_list_hit = [self.snd_hit1, self.snd_hit2, self.snd_hard1, self.snd_hard2]
def add_sound(self, file):
new_sound = pygame.mixer.Sound(file)
self.snd_master_list.append(new_sound)
return new_sound
def sound_adjust(self):
for sound in self.snd_master_list:
sound.set_volume(PREF.vol_sound)
pygame.mixer.music.set_volume(PREF.vol_music)
class obj_Game:
def __init__(self) -> None:
self.current_obj = []
self.message_log = []
self.maps_next = []
self.maps_previous = []
self.current_map, self.current_rooms = map_create()
def transition_next(self):
global FOV_CALCULATE
FOV_CALCULATE = True
self.maps_previous.append((PLAYER.x, PLAYER.y, self.current_map, self.current_rooms, self.current_obj))
if len(self.maps_next) == 0:
# append
self.current_obj = [PLAYER]
self.current_map, self.current_rooms = map_create()
map_place_objects(self.current_rooms)
else:
(PLAYER.x, PLAYER.y, self.current_map, self.current_rooms, self.current_obj) = self.maps_next.pop()
map_make_fov(self.current_map)
def transition_previous(self):
global FOV_CALCULATE
FOV_CALCULATE = True
if len(self.maps_previous) != 0:
# insert current level into next at start of list
self.maps_next.append((PLAYER.x, PLAYER.y, self.current_map, self.current_rooms, self.current_obj))
(PLAYER.x, PLAYER.y, self.current_map, self.current_rooms, self.current_obj) = self.maps_previous.pop()
map_make_fov(self.current_map)
class obj_Actor:
def __init__(self, x: int, y: int, name_object: str, animation_key: str, depth=0,
creature: object = None, ai: object = None, container: object = None, item: object = None,
equipment: object = None, stairs: object = None, portal: object = None) -> None:
self.x = x
self.y = y
self.name_object = name_object
self.animation_key = animation_key
self.depth = depth
self.animation_speed = 0.5 # TODO change to variable in seconds
self.animation_cell = 0
self.state = None
# animation ticker
self.flicker = (self.animation_speed / len(ASSETS.animation_dict[self.animation_key]))
self.flicker_timer = 0
self.creature = creature
if creature:
self.creature.owner = self
self.ai = ai
if ai:
self.ai.owner = self
self.container = container
if container:
self.container.owner = self
self.item = item
if item:
self.item.owner = self
self.equipment = equipment
if equipment:
self.equipment.owner = self
if not self.item:
item = com_Item()
self.item = item
self.item.owner = self
self.stairs = stairs
if stairs:
self.stairs.owner = self
self.portal = portal
if portal:
self.portal.owner = self
@property
def display_name(self) -> str:
if self.creature:
return self.creature.name_instance + " " + self.name_object
elif self.equipment and self.equipment.equipped:
return self.name_object + " (E)"
else:
return self.name_object
def draw(self) -> None:
is_visable = libtcod.map_is_in_fov(FOV_MAP, self.x, self.y)
draw_animation = ASSETS.animation_dict[self.animation_key]
if is_visable:
if len(draw_animation) == 1:
SURFACE_MAP.blit(draw_animation[0], (self.x * constants.CELL_WIDTH, self.y * constants.CELL_HEIGHT))
elif len(draw_animation) > 1:
if CLOCK.get_fps() > 0.0:
self.flicker_timer += 1 / CLOCK.get_fps()
if self.flicker_timer >= self.animation_speed:
# reset timer
self.flicker_timer = 0
if self.animation_cell >= len(draw_animation) - 1:
# reset animation
self.animation_cell = 0
else:
self.animation_cell += 1
SURFACE_MAP.blit(draw_animation[self.animation_cell],
(self.x * constants.CELL_WIDTH, self.y * constants.CELL_HEIGHT))
def distance_to(self, coords: PosXY) -> int:
ox, oy = coords
dx = ox - self.x
dy = oy - self.y
return int(math.sqrt(dx ** 2 + dy ** 2))
def move_towards(self, coords: PosXY) -> None:
ox, oy = coords
dx = ox - self.x
dy = oy - self.y
distance = math.sqrt(dx ** 2 + dy ** 2)
dx = int(round(dx / distance))
dy = int(round(dy / distance))
self.creature.move(dx, dy)
def move_away(self, coords: PosXY) -> None:
ox, oy = coords
dx = self.x - ox
dy = self.y - oy
distance = math.sqrt(dx ** 2 + dy ** 2)
dx = int(round(dx / distance))
dy = int(round(dy / distance))
self.creature.move(dx, dy)
class obj_Spritesheet:
"""Pull sprite from a sheet"""
def __init__(self, file_name: str) -> None:
self.sprite_sheet = pygame.image.load(file_name).convert()
self.tiledict = {char: index for index, char in enumerate(string.ascii_lowercase, 1)}
def get_Sprite(self, col: int, row: int, width: int = constants.CELL_WIDTH, height: int = constants.CELL_HEIGHT,
scale=None) -> list:
""" Scale is a Tuple """
sprite_list = []
sprite = pygame.Surface([width, height])
sprite.blit(self.sprite_sheet, (0, 0), [col * width, row * height, width, height])
sprite.set_colorkey(constants.COLOR_BLACK)
if scale:
(new_w, new_h) = scale
sprite = pygame.transform.scale(sprite, (new_w, new_h))
sprite_list.append(sprite)
return sprite_list
def get_Animation(self, num_sprite: int, col: str, row: int, width: int = constants.CELL_WIDTH,
height: int = constants.CELL_HEIGHT, scale: tuple = None) -> list:
""" Scale is a Tuple """
sprite_list = []
for i in range(num_sprite):
sprite = pygame.Surface([width, height])
sprite.blit(self.sprite_sheet, (0, 0),
[self.tiledict[col] * width + (width * i), row * height, width, height])
sprite.set_colorkey(constants.COLOR_BLACK)
if scale:
(new_w, new_h) = scale
sprite = pygame.transform.scale(sprite, (new_w, new_h))
sprite_list.append(sprite)
return sprite_list
class obj_Room:
""" Rectangle room lives on the map"""
def __init__(self, coords: PosXY, size: tuple) -> None:
self.x1, self.y1 = coords
self.w, self.h = size
self.x2 = self.x1 + self.w
self.y2 = self.y1 + self.h
@property
def center(self) -> PosXY:
center_x = int((self.x1 + self.x2) / 2)
center_y = int((self.y1 + self.y2) / 2)
return (center_x, center_y)
def intersect(self, other: object) -> bool:
""" returns true if obj intersects with this one
Adjusted for the walls """
object_intersect = (self.x1 <= other.x2 + 1 and self.x2 >= other.x1 - 1 and
self.y1 <= other.y2 + 1 and self.y2 >= other.y1 - 1)
return object_intersect
class obj_Camera:
def __init__(self):
self.width = constants.CAMERA_WIDTH
self.height = constants.CAMERA_HEIGHT
self.cam_x, self.cam_y = (0, 0)
def update(self):
target_x = PLAYER.x * constants.CELL_WIDTH + (constants.CELL_WIDTH / 2)
target_y = PLAYER.y * constants.CELL_HEIGHT + (constants.CELL_HEIGHT / 2)
distance_x, distance_y = self.map_dist((target_x, target_y))
self.cam_x += int(distance_x * .1)
self.cam_y += int(distance_y * .1)
def win_to_map(self, coords: PosXY) -> tuple:
cdx, cdy = self.camera_dist(coords)
map_p_x = self.cam_x + cdx
map_p_y = self.cam_y + cdy
return (map_p_x, map_p_y)
def map_dist(self, coords: PosXY) -> tuple:
new_x, new_y = coords
dx = new_x - self.cam_x
dy = new_y - self.cam_y
return (dx, dy)
def camera_dist(self, coords: PosXY) -> tuple:
new_x, new_y = coords
dx = new_x - (self.width / 2)
dy = new_y - (self.height / 2)
return (dx, dy)
@property
def rectangle(self):
pos_rect = pygame.Rect((0, 0), (constants.CAMERA_WIDTH, constants.CAMERA_HEIGHT))
pos_rect.center = (self.cam_x, self.cam_y)
return pos_rect
@property
def map_pos(self) -> PosXY:
map_x = int(self.cam_x / constants.CELL_WIDTH)
map_y = int(self.cam_y / constants.CELL_HEIGHT)
return (map_x, map_y)
#
# COMPONENTS
#
class com_Creature:
def __init__(self, name_instance: str, max_hp: int = 10, base_atk: int = 2, base_def: int = 0,
death_function: Any = None):
self.name_instance = name_instance
self.hp = max_hp
self.base_atk = base_atk
self.base_def = base_def
self.max_hp = max_hp
self.death_function = death_function
def move(self, dx: int, dy: int) -> None:
tile_is_wall = (GAME.current_map[self.owner.x + dx][self.owner.y + dy].block_path == True)
target = map_check_for_creatures(self.owner.x + dx, self.owner.y + dy, self.owner)
if target:
self.attack(target)
if not tile_is_wall and target == None:
self.owner.x += dx
self.owner.y += dy
def attack(self, target: Type[obj_Actor]) -> None:
damage = self.power - target.creature.defense
game_message(
('{0} attacks {1} for {2} damage'.format(self.name_instance, target.creature.name_instance, damage)),
constants.COLOR_WHITE)
target.creature.take_damage(damage)
if damage > 0 and self.owner is PLAYER:
hit_sound = random.choice(ASSETS.snd_list_hit)
hit_sound.play()
def take_damage(self, damage: int) -> None:
self.hp -= damage
game_message((self.name_instance + "'s hp is " + str(self.hp) + '/' + str(self.max_hp)), constants.COLOR_WHITE)
if self.hp <= 0:
if self.death_function is not None:
self.death_function(self.owner)
def heal_self(self, val: int) -> None:
self.hp += val
if self.hp > self.max_hp:
self.hp = self.max_hp
game_message((self.name_instance + "'s hp is " + str(self.hp) + '/' + str(self.max_hp)), constants.COLOR_WHITE)
@property
def power(self) -> int:
total = self.base_atk
if self.owner.container:
obj_bonus = [obj.equipment.attack_bonus for obj in self.owner.container.equipped_items]
for bonus in obj_bonus:
total += bonus
return total
@property
def defense(self) -> int:
total = self.base_def
if self.owner.container:
obj_bonus = [obj.equipment.defense_bonus for obj in self.owner.container.equipped_items]
for bonus in obj_bonus:
total += bonus
return total
class com_Item:
def __init__(self, use_function: Any = None, value: Any = 0, weight: float = 0.0, volume: float = 0.0):
self.weight = weight
self.volume = volume
self.use_function = use_function
self.value = value
self.container = None
def pickup(self, actor: Type[obj_Actor]) -> None:
if actor.container:
if actor.container.volume + self.volume > actor.container.base_volume:
# TODO wrong msg if actor is a monster
game_message('Not enough room to pick up')
else:
game_message('Picking up items')
actor.container.inventory.append(self.owner)
GAME.current_obj.remove(self.owner)
self.container = actor.container
def drop(self, new_x: int, new_y: int) -> None:
# TODO need to select the item to drop
GAME.current_obj.append(self.owner)
self.remove()
self.owner.x = new_x
self.owner.y = new_y
game_message('Item Dropped')
def use(self) -> None:
""" Triggers the use of the Item"""
if self.owner.equipment:
self.owner.equipment.toggle_equipped()
return
if self.use_function:
result = self.use_function(self.container.owner, self.value)
if result is None:
self.remove()
def remove(self) -> None:
self.container.inventory.remove(self.owner)
self.container = None
## TODO view item
class com_Container:
def __init__(self, volume: float = 10.0, inventory: list = []) -> None:
# List for inventory
self.inventory = inventory
self.base_volume = volume
## TODO get names from inventory
@property
## TODO get the volume
def volume(self):
return 0.0
## TODO get weight of items
@property
def equipped_items(self) -> list:
list_equipped = [obj for obj in self.inventory if obj.equipment and obj.equipment.equipped]
return list_equipped
class com_Equipment:
def __init__(self, attack_bonus: int = 0, defense_bonus: int = 0, slot: str = None):
self.attack_bonus = attack_bonus
self.defense_bonus = defense_bonus
self.slot = slot
self.equipped = False
def toggle_equipped(self) -> None:
if self.equipped:
self.unequip()
else:
self.equip()
def equip(self) -> None:
# check equipment in slot and swap
equ_items = self.owner.item.container.equipped_items
for item in equ_items:
if item.equipment.slot == self.slot:
item.equipment.unequip()
self.equipped = True
game_message('item equipped')
def unequip(self) -> None:
self.equipped = False
game_message('item unequipped')
class com_Stairs:
def __init__(self, downwards=True):
self.downwards = downwards
def use(self):
if self.downwards:
GAME.transition_next()
else:
GAME.transition_previous()
class com_Portal:
def __init__(self, key: str):
self.portalclosed = "S_PORTAL_CLOSED"
self.portalopen = "S_PORTAL_OPEN"
self.key = key
self.open = False
self.found_key = False
def update(self):
for item in PLAYER.container.inventory:
if self.key == item.item.value:
self.found_key = True
break
else:
self.found_key = False
if self.found_key and not self.open:
self.owner.animation_key = self.portalopen
self.open = True
elif not self.found_key and self.open:
self.open = False
self.owner.animation_key = self.portalclosed
#
# AI
#
class ai_Confused:
def __init__(self, old_ai: object, turns: int):
self.old_ai = old_ai
self.turns = turns
def take_turn(self) -> None:
if self.turns >= 0:
self.owner.creature.move(libtcod.random_get_int(0, -1, 1), libtcod.random_get_int(0, -1, 1))
self.turns -= self.turns
else:
self.owner.ai = self.old_ai
self.owner.ai.owner = self.owner
game_message('{0} has recovered'.format(self.owner.name_object), constants.COLOR_RED)
class ai_Chase:
def take_turn(self) -> None:
monster = self.owner
if libtcod.map_is_in_fov(FOV_MAP, monster.x, monster.y):
if monster.distance_to((PLAYER.x, PLAYER.y)) >= 2:
monster.move_towards((PLAYER.x, PLAYER.y))
else:
monster.creature.attack(PLAYER)
class ai_Flee:
def take_turn(self) -> None:
monster = self.owner
if libtcod.map_is_in_fov(FOV_MAP, monster.x, monster.y):
monster.move_away((PLAYER.x, PLAYER.y))
#
# DEATH
#
def death_snake(snake: Type[obj_Actor]) -> None:
game_message(snake.creature.name_instance + ' is dead', constants.COLOR_RED)
snake.animation_key = "S_CORPSE"
snake.depth = constants.DEPTH_CORPSE
snake.creature = None
snake.ai = None
def death_mouse(mouse: Type[obj_Actor]) -> None:
game_message(mouse.creature.name_instance + ' is dead. Eat for more health', constants.COLOR_GREEN)
mouse.animation_key = "S_CORPSE_HP"
mouse.depth = constants.DEPTH_CORPSE
mouse.creature = None
mouse.ai = None
def death_player(player: Type[obj_Actor]) -> None:
player.state = "STATUS_DEAD"
SURFACE_MAIN.fill(constants.COLOR_BLACK)
draw_text(SURFACE_MAIN, "You're Dead", constants.FONT_TITLE,
(constants.CAMERA_WIDTH / 2, constants.CAMERA_HEIGHT / 2),
constants.COLOR_RED, center=True)
filename = ("data\legacy_" + player.name_object + "." + datetime.date.today().strftime("%Y%B%d"))
legacy_file = open(filename, 'a+')
for message, color in GAME.message_log:
legacy_file.write(message + "\n")
files_delete('data\savegame')
pygame.display.update()
pygame.time.wait(2000)
def win_player(player: Type[obj_Actor]) -> None:
player.state = "STATUS_WIN"
SURFACE_MAIN.fill(constants.COLOR_BLACK)
game_message('{0} has escaped the Snake Pit'.format(player.name_object), constants.COLOR_WHITE)
draw_text(SURFACE_MAIN, "You're Escaped!", constants.FONT_TITLE,
(constants.CAMERA_WIDTH / 2, constants.CAMERA_HEIGHT / 2),
constants.COLOR_WHITE, center=True)
filename = ("data\win_" + player.name_object + "." + datetime.date.today().strftime("%Y%B%d"))
legacy_file = open(filename, 'a+')
for message, color in GAME.message_log:
legacy_file.write(message + "\n")
files_delete('data\savegame')
pygame.display.update()
pygame.time.wait(2000)
#
# MAPPING
#
def map_create():
new_map = [[str_Tile(True) for y in range(0, constants.MAP_HEIGHT)] for x in range(0, constants.MAP_WIDTH)]
list_rooms = []
for i in range(constants.MAP_MAX_ROOMS):
w = random.randint(constants.ROOM_MIN_WIDTH, constants.ROOM_MAX_WIDTH)
h = random.randint(constants.ROOM_MIN_HEIGHT, constants.ROOM_MAX_HEIGHT)
x = random.randint(2, constants.MAP_WIDTH - w - 2)
y = random.randint(2, constants.MAP_HEIGHT - h - 2)
new_room = obj_Room((x, y), (w, h))
intersect_check = False
for other_room in list_rooms:
if new_room.intersect(other_room):
intersect_check = True
break
if not intersect_check:
map_create_room(new_map, new_room)
center = new_room.center
if len(list_rooms) != 0:
prev_center = list_rooms[-1].center
map_create_tunnels(center, prev_center, new_map)
list_rooms.append(new_room)
map_make_fov(new_map)
return (new_map, list_rooms)
def map_place_objects(room_list: list) -> None:
top_level = (len(GAME.maps_previous) == 0)
for room in room_list:
first_room = (room == room_list[0])
last_room = (room == room_list[-1])
if first_room:
PLAYER.x, PLAYER.y = room.center
if not top_level:
gen_Stairs(room.center, downwards=False)
else:
gen_Portal(room.center, key='Magic Lamp')
if last_room:
if len(GAME.maps_previous) == constants.MAP_MAX_DEPTH-1:
gen_magic_lamp(room.center, "Magic Lamp")
else:
gen_Stairs(room.center, downwards=True)
item_x = random.randint(room.x1, room.x2)
item_y = random.randint(room.y1, room.y2)
gen_item((item_x, item_y))
mob_x = random.randint(room.x1, room.x2)
mob_y = random.randint(room.y1, room.y2)
gen_enemy((mob_x, mob_y))
def map_create_tunnels(coords1: PosXY, coords2: PosXY, new_map: list) -> None:
x1, y1 = coords1
x2, y2 = coords2
coin = (random.randint(0, 1) == 1)
if coin:
for x in range(min(x1, x2), max(x1, x2) + 1):
new_map[x][y1].block_path = False
for y in range(min(y1, y2), max(y1, y2) + 1):
new_map[x2][y].block_path = False
else:
for y in range(min(y1, y2), max(y1, y2) + 1):
new_map[x1][y].block_path = False
for x in range(min(x1, x2), max(x1, x2) + 1):
new_map[x][y2].block_path = False
def map_create_room(new_map, new_room):
for x in range(new_room.x1, new_room.x2 + 1):
for y in range(new_room.y1, new_room.y2 + 1):
new_map[x][y].block_path = False
def map_obj_at_loc(loc_x, loc_y):
""" Returns a list of objects at x,y"""
objects = [obj for obj in GAME.current_obj
if obj.x == loc_x and obj.y == loc_y]
return objects
def map_check_for_creatures(x, y, exclude_obj=None):
target = None
if exclude_obj:
# target self
for obj in GAME.current_obj:
if (obj is not exclude_obj and obj.x == x and obj.y == y and obj.creature):
target = obj
else:
# Target self and others
for obj in GAME.current_obj:
if (obj.x == x and obj.y == y and obj.creature):
target = obj
if target:
return target
def map_make_fov(incoming_map):
global FOV_MAP
FOV_MAP = libtcod.map_new(constants.MAP_WIDTH, constants.MAP_HEIGHT)
for y in range(constants.MAP_HEIGHT):
for x in range(constants.MAP_WIDTH):
libtcod.map_set_properties(FOV_MAP, x, y,
not incoming_map[x][y].block_path, not incoming_map[x][y].block_path)
def map_calculate_fov():
global FOV_CALCULATE
if FOV_CALCULATE:
FOV_CALCULATE = False
libtcod.map_compute_fov(FOV_MAP, PLAYER.x, PLAYER.y, constants.TORCH_RAD, constants.FOV_LIGHT_WALLS,
constants.FOV_ALGO)
def map_find_line(coords1, coords2):
x1, y1 = coords1
x2, y2 = coords2
libtcod.line_init(x1, y1, x2, y2)
line_x, line_y = libtcod.line_step()
coord_list = []
if x1 == x2 and y1 == y2:
return [(x1, y1)]
while line_x is not None:
coord_list.append((line_x, line_y))
# Step Step
line_x, line_y = libtcod.line_step()
return coord_list
def map_find_radius(coords, radius):
# Simple radius not trimming edges
center_x, center_y = coords
cell_list = []
for x in range((center_x - radius), (center_x + radius + 1)):
for y in range((center_y - radius), (center_y + radius + 1)):
cell_list.append((x, y))
return cell_list
#
# DRAWING
#
def draw_game():
global SURFACE_MAIN
# clear the surface
SURFACE_MAIN.fill(constants.COLOR_DEFAULT_BG)
SURFACE_MAP.fill(constants.COLOR_BLACK)
CAMERA.update()
# draw the map
draw_map(GAME.current_map)
# draw character
for obj in sorted(GAME.current_obj, key=lambda obj: obj.depth, reverse=True):
obj.draw()
SURFACE_MAIN.blit(SURFACE_MAP, (0, 0), CAMERA.rectangle)
draw_debug()
draw_message()
# update the display
pygame.display.flip()
def draw_map(map_to_draw):
cam_x, cam_y = CAMERA.map_pos
display_map_w = constants.CAMERA_WIDTH / constants.CELL_WIDTH
display_map_h = constants.CAMERA_WIDTH / constants.CELL_HEIGHT
render_w_min = int(cam_x - (display_map_w / 2))
render_h_min = int(cam_y - (display_map_h / 2))
render_w_max = int(cam_x + (display_map_w / 2))
render_h_max = int(cam_y + (display_map_h / 2))
if render_w_min < 0: render_w_min = 0
if render_h_min < 0: render_h_min = 0
if render_w_max > constants.MAP_WIDTH: render_w_max = constants.MAP_WIDTH
if render_h_max > constants.MAP_HEIGHT: render_h_max = constants.MAP_HEIGHT
for x in range(render_w_min, render_w_max):
for y in range(render_h_min, render_h_max):
is_visible = libtcod.map_is_in_fov(FOV_MAP, x, y)
if is_visible:
map_to_draw[x][y].seen = True
if map_to_draw[x][y].block_path:
# draw wall
SURFACE_MAP.blit(ASSETS.S_WALL, (x * constants.CELL_WIDTH, y * constants.CELL_HEIGHT))
else:
# draw floor
SURFACE_MAP.blit(ASSETS.S_FLOOR, (x * constants.CELL_WIDTH, y * constants.CELL_HEIGHT))
elif map_to_draw[x][y].seen:
if map_to_draw[x][y].block_path:
# draw wall
SURFACE_MAP.blit(ASSETS.S_WALL_UNSEEN, (x * constants.CELL_WIDTH, y * constants.CELL_HEIGHT))
else:
# draw floor
SURFACE_MAP.blit(ASSETS.S_FLOOR_UNSEEN, (x * constants.CELL_WIDTH, y * constants.CELL_HEIGHT))
def draw_debug():
draw_text(SURFACE_MAIN,
"FPS: " + str(int(CLOCK.get_fps())),
constants.FONT_DEBUG,
(0, 0),
constants.COLOR_RED,
constants.COLOR_BLACK)
def draw_text(display_surface, text, font, coords: PosXY, text_color, back_color=None, center=False):
text_surf, text_rect = helper_text_object(text, font, text_color, back_color)
if not center:
text_rect.topleft = coords
else:
text_rect.center = coords
display_surface.blit(text_surf, text_rect)
def draw_message():
""" Draw Message Logger Text showing only the MESSAGE_LOG_NUM amount of messages"""
if len(GAME.message_log) <= constants.MESSAGE_LOG_NUM:
to_draw = GAME.message_log
else:
to_draw = GAME.message_log[-constants.MESSAGE_LOG_NUM:]
text_height = helper_text_height(constants.FONT_MESSAGE)
start_y = (constants.CAMERA_HEIGHT - (constants.MESSAGE_LOG_NUM * text_height)) - 5
i = 0
for message, color in to_draw:
draw_text(SURFACE_MAIN, message, constants.FONT_MESSAGE, (0, start_y + (i * text_height)), color)
i += 1
def draw_tile_rect(coords: PosXY, color=constants.COLOR_WHITE, marker=None):
""" Draws a Cell rect on the MAP surface """
new_surface = pygame.Surface((constants.CELL_WIDTH, constants.CELL_HEIGHT))
new_surface.fill(color)
new_surface.set_alpha(100)
draw_text(new_surface, marker, constants.FONT_CURSOR_TEXT,
coords=(constants.CELL_WIDTH / 2, constants.CELL_HEIGHT / 2),
text_color=constants.COLOR_BLACK, center=True)
SURFACE_MAP.blit(new_surface, coords)
#
# HELPERS
#
def helper_text_object(text, font, color, bg_color):
if bg_color:
text_surface = font.render(text, False, color, bg_color)
else:
text_surface = font.render(text, False, color)
return text_surface, text_surface.get_rect()
def helper_text_height(font):
font_rect = font.render('a', False, (0, 0, 0)).get_rect()
return font_rect.height
def helper_text_width(font, text):
font_rect = font.render(text, False, (0, 0, 0)).get_rect()
return font_rect.width
def screen_mid_offset(width, height):
""" Determines the middle point offset for a screen or text """