-
Notifications
You must be signed in to change notification settings - Fork 0
/
rlboys.py
2363 lines (1763 loc) · 94.4 KB
/
rlboys.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
#if anyone attempts to read this code
#i am not responsible
import libtcodpy as libtcod
import math
import textwrap
import shelve
from random import gauss, uniform
from collections import deque
from ritualdraw import RitualDraw
from render import *
#===============#
import catalog
import graphical
import AI
from utility import *
from sett import *
from messages import *
#TODO: big todos:
#TODO: Graphical effects(floating text, floating numbers maybe, blood, buff effects)##floating text done
#TODO: map generation
#TODO: some actual interesting enemies, AI
#TODO: staves, ranged weapons, polearms, cudgels
#TODO: more weapons, more enemies, more consumables
#TODO: fill out skill, perk trees
#TODO: subskill system***?
#TODO: separate combat abilities
class PlayerStats(object):
def __init__(self, stats):
self.basestats = stats #dict
self.strength = stats['strength']
self.agility = stats['agility']
self.constitution = stats['constitution']
self.intelligence = stats['intelligence']
self.attunement = stats['attunement']
class DrawingDir(object):
def __init__(self): #keeps record of ritual drawings on the ground that are not yet activated, since I want the player to be able to have multiple of them set up at once
self.drawinglist = []
def clear(self):
for drawing in self.drawinglist: self.drawinglist.remove(drawing)
@property
def active_drawing(self):
try:
active = filter(lambda x: x.concluded == False, self.drawinglist)
return active[0]
except:
print '####################################################'
print 'WARNING: Call for active drawing that did not exist'
print '####################################################'
class GlobalDir(object):# globals not in here: camera, con, panel, director
def __init__(self):
self.game_objs = []
self.colorkeeper = {}
self.namekeeper = {}
self.dungeon_level = 1
self.drawdir = DrawingDir()
self.noisemap = libtcod.heightmap_new(MAP_WIDTH,MAP_HEIGHT)
self.processnoise = False
self.game_msgs = []
self.game_state = 'playing'
def create_noise(self, origin, noisevalue):#self, gldir)
#this shouldnt be here but it's a clean way to do it and i don't care
x = origin.x
y = origin.y
currentnoise = libtcod.heightmap_get_value(self.noisemap, x, y)
radius = (currentnoise + noisevalue) * 4
libtcod.heightmap_add_hill(self.noisemap, x, y, radius, noisevalue)#noisemap clamped at 10, loudest possible
self.processnoise = True
class PlayerActionReport(object):
def __init__(self, action = None, x1 = None, y1 = None, x2 = None, y2 = None, objects = None, action_extra = None, takes_turn = True):
self.action = action
self.action_extra = action_extra #
self.takes_turn = takes_turn #
self.x1 = x1 #This object reports on the last action taken by the player, as well as keeping a record of the last however many actions in a list(number decided in add_to_recorder),
self.y1 = y1 #Remember to add a director update call to every player action
self.x2 = x2 #
self.y2 = y2 #
self.objects = objects # objects involved in the last action, not the global
self.recorder = deque([], 20) # double ended queue from collections, makes deleting old actions automatic
def __dir__(self):
return ['action', 'x1', 'y1', 'y2', 'x2', 'objects', 'action_extra', 'takes_turn']
def update(self, **kwargs):#kwarg keywords must be attributes. This function updates the director singleton with the attributes passed, then sets all of its other attributes to standard values defined at the bottom(or None if there are no defaults)
global director
for keyword, value in kwargs.iteritems():
try: setattr(self, keyword, value)
except: raise ValueError('!!!!!ERROR!!!!!: Probably a parameter name error in an update call:', keyword, value, '\ninvolving objects:', objects)
setnone = filter(lambda x: x not in kwargs, [attr for attr in dir(self)]) #setnone is the list of PlayerActionReport attributes that were not in the kwargs passed, to be set to none or a default
for attrname in setnone:
try: setattr(self, attrname, None)
except: raise ValueError('Something has gone wrong with the game director. Check what got passed through director.update', attrname, setnone, dir(self))
if 'takes_turn' not in kwargs: self.takes_turn = True
if 'x1' not in kwargs: self.x1 = gldir.player.x
if 'y1' not in kwargs: self.y1 = gldir.player.y
self.add_to_recorder()
def add_to_recorder(self): #records every player action(aka every separate state taken by the director singleton). Saved as a list of dictionaries, with key names equal to the playeractionreport attribute names
record_dict = {}
for attribute in dir(self):
record_dict[attribute] = self.__dict__[attribute]
self.recorder.append(record_dict)
# if len(self.recorder) > 50: self.recorder.pop(0) #rolling list
#commented out because the max length is set by deque in the __init__ of this object
class SkillTree:#DO NOT NEED TO BE GLOBAL. I can have them easily belong to the Player obj
#to change later
def __init__(self, stype, level = 0):
self.stype = stype
self.level = level
self.nodetable = catalog.get_nodetable(stype)
for node in self.nodetable:
node.owner = self
def get_node_from_name(self, name):
for node in self.nodetable:
if node.name == name: return node
def get_available_nodes(self):
available_nodes = []
for node in self.nodetable:
if (node.parent == [] or node.parent == '' or check_if_node_leveled(self, node.parent)) and not node.leveled:
available_nodes.append(node)
if available_nodes == []: textbox('No nodes to select.')
else: return available_nodes
def node_select(self):
width = SCREEN_WIDTH
height = SCREEN_HEIGHT
ended = False
skillbox = libtcod.console_new(width, height)
options = self.get_available_nodes()
letter_index = ord('a')
y=2
libtcod.console_print_frame(skillbox,0, 0, width, height, clear=False, flag=libtcod.BKGND_DEFAULT, fmt=None) #god i hate making menus
for node in options:
text = ' ' + chr(letter_index) +' - ' + node.name
libtcod.console_print_ex(skillbox, 2, y, libtcod.BKGND_NONE, libtcod.LEFT, text)
y += 2
letter_index += 1
libtcod.console_blit(skillbox,0,0,0,0,0,0,0)
libtcod.console_flush()
choice = False
while True:
libtcod.console_flush()
key = libtcod.console_wait_for_keypress(True)
if key.vk == libtcod.KEY_ENTER:
if choice:
choice.levelup()
return True
else:
textbox('No node chosen.')
continue
elif key.vk == libtcod.KEY_ESCAPE:
return
index = key.c - ord('a')
choice = options[index]
self.node_description(choice)
def node_description(self, node):
width = SCREEN_WIDTH -6
height = SCREEN_HEIGHT/2 -2
skillcon = libtcod.console_new(width, height)
libtcod.console_print_frame(skillcon,0, 0, width, height, clear=False, flag=libtcod.BKGND_DEFAULT, fmt=None)
print node.name
description = catalog.get_node_description(node.name) ##
for line in description:
libtcod.console_print_ex(skillcon, 1, description.index(line)+1,libtcod.BKGND_NONE, libtcod.LEFT, line)
libtcod.console_print_ex(skillcon, 1, 60, libtcod.BKGND_NONE, libtcod.LEFT, 'Press enter to accept selection')
libtcod.console_blit(skillcon, 0, 0, 0, 0, 0, 2, height + 2)
@property
def level(self):
maxlvl = 0
for node in self.nodetable:
if node.leveled and node.tier > maxlvl: maxlvl = node.tier #tree level is = to highest skill node tier
return maxlvl
class PerkTree(SkillTree):
def get_available_nodes(self):
for node in self.nodetable:
if pass_perk_requirements(node) and (node.parent == [] or node.parent == '' or check_if_node_leveled(self, node.parent)) and not node.leveled:
available_nodes.append(node)
if available_nodes == []: textbox('No nodes to select.')
else: return available_nodes
#SKILL TREE DATA STRUCTURE:
#One SkillTree (perktree inherited for perks) object for each type (combat, tech, ritual, perks), each containing appropriate nodetable objects gotten from the catalog
#abilities are passed on to the player in the Player's abilities property whenever they are called (getter decorator)
#haven't done passive bonuses yet
class Ccreation:
def __init__(self, stage = 'race select', chosenrace = 'empty', chosengclass = 'empty', chosenperk = 'empty'):
self.stage = stage
self.chosenrace = chosenrace
self.chosengclass = chosengclass
self.chosenperk = chosenperk
def run_creation(self):
global gldir
gldir = GlobalDir()
gldir.player = Player()
gldir.player.ctree = SkillTree('combat', 1)
gldir.player.ttree = SkillTree('tech', 0)
gldir.player.rtree = SkillTree('ritual', 0)
gldir.player.ptree = PerkTree('perks', 0)
while self.stage != 'complete':
if self.stage == 'race select':
self.descriptionbox(self.chosenrace)
self.statbox(self.chosenrace)
self.chosenrace = self.choicebox()
elif self.stage == 'class select': #loops between this and choicebox until creation is done
self.descriptionbox(self.chosengclass)
self.statbox(self.chosengclass)
self.chosengclass = self.choicebox()
elif self.stage == 'skill select':
tree_lvlup()
self.stage = 'complete'
clear_screen()
elif self.stage == 'quit out':
main_menu()
# elif self.stage == 'perk select':
#initalize player later here
#return Player(self.chosenrace, self.chosengclass,)
def statbox(self,choice): # draws stat box(bottom half)
width = SCREEN_WIDTH -6
height = SCREEN_HEIGHT/2 -2
statsbox = libtcod.console_new(width, height)
libtcod.console_print_frame(statsbox,0, 0, width, height, clear=False, flag=libtcod.BKGND_DEFAULT, fmt=None)
try: statblock = catalog.ccreation_stats(choice) ## text for the statblock, comes in a list of strings
except: statblock = ["this description hasn't been written yet!"]
for line in statblock:
libtcod.console_print_ex(statsbox, 1, statblock.index(line)+1,libtcod.BKGND_NONE, libtcod.LEFT, line)
libtcod.console_print_ex(statsbox, 1, 60, libtcod.BKGND_NONE, libtcod.LEFT, 'Press enter to accept selection')
libtcod.console_blit(statsbox, 0, 0, 0, 0, 0, 2, height + 2) #creates and prints to the statbox that takes up the lower half of the screen in char creation
def descriptionbox(self,choice): #draws description box (top right)
width = SCREEN_WIDTH/3 - 2
height = SCREEN_HEIGHT/2
description_box = libtcod.console_new(width, height)
libtcod.console_set_alignment(description_box, libtcod.CENTER)
text = catalog.ccreation_description(choice)
libtcod.console_print_rect(description_box, width/2+2, height*2/3, width-5, height, text)
libtcod.console_print_frame(description_box,0, 0, width, height, clear=False, flag=libtcod.BKGND_DEFAULT, fmt=None)
libtcod.console_blit(description_box, 0, 0, 0, 0, 0, (width*2)+2, 0) #creates and prints to the description box that takes up the upper left side of the screen in char creation
def choicebox(self):
width = (SCREEN_WIDTH*2)/3+1
height = SCREEN_HEIGHT/2
menu_selection = libtcod.console_new(width, height) #
letter_index = ord('a') #
y = 2 #
x = 2 #
if self.stage == 'race select': #
requested_list = catalog.FULL_RACELIST #
elif self.stage == 'class select': #
requested_list = catalog.FULL_GCLASSLIST #
# # all menu creation stuff copy pasta-ed from menu method
for option_text in requested_list: #
text = ' ' + chr(letter_index) +' - ' + option_text #
libtcod.console_print_ex(menu_selection, x, y, libtcod.BKGND_NONE, libtcod.LEFT, text)#
# #
y += 2 #
if y > SCREEN_HEIGHT/2 - 1: #
x += 8 #
y = 2 #
letter_index += 1 #
libtcod.console_print_frame(menu_selection,0, 0, width, height, clear=False, flag=libtcod.BKGND_DEFAULT, fmt=None)
libtcod.console_blit(menu_selection,0,0,0,0,0,2,0)
libtcod.console_flush()
key = libtcod.console_wait_for_keypress(True)
if key.vk == libtcod.KEY_ENTER:
if self.stage == 'race select': # this is where the stage cycling takes place
if self.chosenrace == 'empty':
msgbox("You haven't chosen a race.")
return 'empty'
self.stage = 'class select'
return self.chosenrace
elif self.stage == 'class select':
if self.chosengclass == 'empty':
msgbox("You haven't chosen a class.")
return 'empty'
self.stage = 'skill select'
return self.chosengclass
if key.vk == libtcod.KEY_ESCAPE:
if self.stage == 'class select':
self.stage = 'race select'
return 'empty'
elif self.stage == 'race select':
self.stage = 'quit out'
index = key.c - ord('a')
if index >= 0 and index < len(requested_list):
return requested_list[index] ### returns the name of the chosen class or race or whatever as per catalog list
else: return 'empty'
class Equipment:
def __init__(self, owner, slot, base_dmg = [0,0], armor_bonus = 0, dodge_bonus = 0, twohand = False, equiptype = 'armor'):
self.slot = slot
self.owner = owner
self.is_equipped = False
self.base_dmg = base_dmg
self.dodge_bonus = dodge_bonus
self.armor_bonus = armor_bonus
self.twohand = twohand
self.special = None
self.equiptype = equiptype
self.add_base_specials()
def equip(self,equipper):
#equip object and show a message about it
if equipper == 'player':
if self.twohand and get_equipped_in_slot('off hand'):
message("The " + self.owner.name + ' requires both hands to use.', gldir.game_msgs)
return
if get_equipped_in_slot(self.slot):
get_equipped_in_slot(self.slot).unequip()
self.is_equipped = True
message('Equipped ' + self.owner.item.dname + ' on your ' + self.slot + '.', libtcod.light_green, gldir.game_msgs)
director.update(action = 'equip item', object_s = self.owner)
def unequip(self):
if not self.is_equipped: return
self.is_equipped = False
if self.equiptype == 'staff':
for statusname in ['parry staff stance', 'hammer staff stance', 'spear staff stance']:
status = get_status_from_name(gldir.player, statusname)
if status: status.terminate()
message('Unequipped ' + self.owner.item.dname + ' from ' + self.slot + '.', libtcod.light_yellow, gldir.game_msgs)
director.update(action = 'unequip item', object_s = self.owner)
def equip_options(self): #upon getting chosen from the equipment menu
options = ['Examine', 'Unequip', 'Drop', 'Use']
index = menu('Choose an action: ', options, 50)
if index == 0:
self.owner.item.examine()
return 'examine'
elif index == 1:
self.unequip()
return 'unequip'
elif index == 2: #drop (and unequip)
self.unequip() # this is redundant because it's in the item drop method but i'm gonna leave it here, just in case
self.owner.item.drop()
return 'drop'
elif index == 3: #drop (and unequip)
self.owner.item.use()
return 'use'
def roll_dmg(self):
if self.base_dmg == [0,0]: return 0
else:
return libtcod.random_get_int(0, self.base_dmg[0], self.base_dmg[1])
def add_base_specials(self):
self.special = catalog.EqSpecial(owner = self)
def apply_on_atk_bonus(self, origin, target):
bonusdmg = Dmg(0, 1, 0)
if self.special:
for enchant in self.special.enchantlist: #cycles through EnchantModules
if enchant.name == 'str bonus':
bonusdmg.add(origin.stats['strength'] * enchant.value)
elif enchant.name == 'maim chance':
if libtcod.random_get_float(0,0,1) <= enchant.value:
target.fighter.receive_status('maim', enchant.duration)
message('Your attack maims the enemy!', libtcod.light_blue, gldir.game_msgs)
elif enchant.name == 'stun chance':
if libtcod.random_get_float(0,0,1) <= enchant.value:
target.fighter.receive_status('stun', enchant.duration)
message('Your attack stuns the enemy!', libtcod.light_blue, gldir.game_msgs)
if self.equiptype == 'staff' and get_status_from_name(gldir.player, 'hammer staff stance'):
bonusdmg.add(origin.stats['strength'] * 0.5)
return bonusdmg
class Item:
def __init__(self, owner, weight = 0, depth_level = 1, use_function = None, itemtype = 'gadget', stack = 1):
self.weight = weight
self.owner = owner
self.use_function = use_function
self.depth_level = depth_level
self.identified = False
self.already_seen = False
self.itemtype = itemtype
self.stack = stack
if itemtype in ['trinket', 'chalk']: self.identified = True
#possible itemtypes: equipment, salve, gadget, trinket, chalk
def pick_up(self):
if self.owner.name in map(lambda x: x.name, gldir.player.inventory) and self.itemtype in ['gadget', 'salve', 'chalk']:
invitem = filter(lambda x: x.name == self.owner.name, gldir.player.inventory)
invitem = invitem[0]
invitem.item.stack += self.stack # same thing as normal pickup but just increments to stack
gldir.game_objs.remove(self.owner)
message('You picked up ' + self.dname + '!', libtcod.green, gldir.game_msgs)
director.update(action = 'pick up item', object_s = self.owner)
elif len(gldir.player.inventory)>=26:
message('Your inventory is full', libtcod.white, gldir.game_msgs)
return False
elif sum([item.item.weight for item in gldir.player.inventory]) > gldir.player.max_weight:
message("You're carrying too much already!", libtcod.white, gldir.game_msgs)
return False
else:
gldir.player.inventory.append(self.owner) # inventory has objects, not item
gldir.game_objs.remove(self.owner)
message('You picked up ' + self.dname + '!', libtcod.green, gldir.game_msgs)
director.update(action = 'pick up item', object_s = self.owner)
return True
def use(self):
if not self.use_function:
message('The ' + self.owner.name + ' cannot be used.', libtcod.white, gldir.game_msgs)
elif self.itemtype == "chalk":
self.use_function(self)
elif self.use_function() != 'cancelled' and self.itemtype != 'equipment': #conditions for persistent/charge-based consumables go here
self.stack -= 1
if self.stack < 1: gldir.player.inventory.remove(self.owner)
director.update(action = 'use item', object_s = self.owner)
def drop(self):
#add to the map and remove from the player's inventory. also, place it at the player's coordinates
gldir.game_objs.insert(0,self.owner)
gldir.player.inventory.remove(self.owner)
if self.owner.equipment and self.owner.equipment.is_equipped: self.owner.equipment.unequip()
self.owner.x = gldir.player.x
self.owner.y = gldir.player.y
message('You dropped a ' + self.dname + '.', libtcod.yellow, gldir.game_msgs)
director.update(action = 'drop item', object_s = self.owner)
def examine(self):
text = catalog.get_item_description(self)
director.update(action = 'examine item', object_s = self.owner, takes_turn = False)
textbox(text)
def item_options(self):
options = ['Examine', 'Drop', 'Use']
if self.owner.equipment:
options.append('Equip')
index = menu('Choose an action: ', options, 50)
if index == 0:#examine
self.examine()
return 'examine'
if index == 1: #drop
self.drop()
return 'drop'
if index == 2: #use
self.use()
return 'use'
if options[index] == 'Equip':
self.owner.equipment.equip('player')
return 'equip'
@property
def dname(self):#short for display name
dname = self.owner.name
if self.owner.name in gldir.namekeeper:
self.already_seen = True
if self.stack > 1: dname += ' (' + str(self.stack) + ')'
if not self.identified:
if self.itemtype == 'equipment':
unidname = 'an unidentified ' + self.owner.name
elif self.itemtype == 'salve':
if not self.already_seen:
unidname = catalog.random_salve_name(self)
gldir.namekeeper[self.owner.name] = unidname
else: unidname = gldir.namekeeper[self.owner.name]
elif self.itemtype == 'gadget':
if not self.already_seen:
unidname = catalog.random_gadget_name(self)
gldir.namekeeper[self.owner.name] = unidname
else: unidname = gldir.namekeeper[self.owner.name]
return unidname
else: return dname
@property
def weight(self):
return self._weight * self.stack
@weight.setter
def weight(self, value):
self._weight = value
class StatusEffect(object): #TODO: STACKING BEHAVIOUR FOR STATUS EFFECTS
def __init__(self, name, duration, affected, power = 0):
self.name = name
self.duration = duration
if duration == 0: self.duration = -1 #unlimited
self.affected = affected #affected is fighter
self.startfunction()
self.power = power
def activate(self):
if self.duration == 0:
self.terminate()
else:
self.stepfunction()
def terminate(self):
self.endfunction()
self.affected.status.remove(self)
def startfunction(self):
if self.name == 'maim':
return graphical.FloatingText(self.affected.owner, self.name, libtcod.violet)
if self.name == 'stun':
return graphical.FloatingText(self.affected.owner, self.name, libtcod.yellow)
def stepfunction(self):
if self.name == 'drawing':
if self.pen.stack > 0:
drawing_function(self)
self.pen.stack -= 1
else:
message('You ran out of ' + self.pen.owner.name, libtcod.light_red , gldir.game_msgs)
gldir.player.inventory.remove(self.pen.owner)
self.terminate()
elif self.name == 'DoT':
self.affected.take_damage(round(self.power*0.4))
elif self.name == 'stun':
self.affected.energy = 0
message('The '+ self.affected.owner.name + ' is too stunned to act.', libtcod.light_blue, gldir.game_msgs)
elif self.name == 'sprint':
if isinstance(self.affected.owner, Player):
if director.action == 'move':
gldir.player.act_points -= gldir.player.fighter.speed/3
elif self.name == 'sprint exhaustion':
if isinstance(self.affected.owner, Player):
gldir.player.act_points += gldir.player.fighter.speed/3
self.duration -= 1
def endfunction(self):
if self.name == 'sprint':
message("You stop sprinting. You're exhausted, slowing you down.", libtcod.light_red, gldir.game_msgs)
self.affected.receive_status('sprint exhaustion', 20)
if self.name == 'sprint exhaustion':
message("You're no longer exhausted. You can sprint again.", libtcod.green, gldir.game_msgs)
class Fighter:
def __init__(self, hp, armor, power, xp, death_function = None, depth_level = 1, speed = 100):
self.max_hp = hp
self.hp = hp
self.base_armor = armor
self.base_power = power
self.death_function = death_function
self.depth_level = depth_level
self.xp = xp
self.state = 'normal'
self.status = []
self.energy = 0
self.speed = speed
self.dodge = 0 # enemies don't usually dodge atm, so this is a hacky fix to make monsters able to attack other monsters
def take_damage(self,damage):
if isinstance(damage, Dmg): damage = damage.resolve()
if damage > 0:
self.hp -= damage
if self.hp < 0:
gldir.player.fighter.xp += self.xp
function = self.death_function
if function is not None:
function(self.owner)
def receive_status(self, statusname, duration, power = 0):
status = StatusEffect(statusname, duration, self, power)
self.status.append(status)
def attack(self, target):
if isinstance(self.owner, Player):
multiattack = get_multiattack_number()
for i in range(multiattack):
if not target.fighter: break #if target dies in between multiattacks, exit loop
damage = self.power()
weapon = get_equipped_in_slot('main hand')
for equip in get_all_equipped(self.owner):#equivalent to global player
damage.add(equip.apply_on_atk_bonus(self.owner, target))
if weapon and weapon.equiptype == 'polearm':
if self.owner.distance_to(target) < 2:
polearm_penalty = get_enchant_value(get_equipped_in_slot('main hand'), 'polearm reach')
damage.add(Dmg(0, polearm_penalty, 0)) #multiplier
if weapon and weapon.equiptype == 'staff' and get_status_from_name(gldir.player, 'spear staff stance') and self.owner.distance_to(target) < 2:
damage.add(Dmg(0, 0.5, 0))
finaldmg = damage.resolve()
finaldmg -= target.fighter.armor
if finaldmg < 0: finaldmg = 0
message('You attack the ' + target.name + ' for ' + str(int(round(finaldmg))) + ' hit points.', libtcod.white, gldir.game_msgs)
target.fighter.take_damage(finaldmg)
director.update(action = 'attack', x2 = target.x, y2 = target.y)
else:
if libtcod.random_get_int(0, 1, 100) > int(round(target.dodge * 1.3)):
damage = self.power() - target.fighter.armor
if damage > 0:
message(self.owner.name.capitalize() + ' attacks ' + target.name + ' for ' + str(int(round(damage))) + ' hit points.', libtcod.white, gldir.game_msgs)
target.fighter.take_damage(damage)
else:
message(self.owner.name.capitalize() + ' attacks ' + target.name + ' but it has no effect!', libtcod.white, gldir.game_msgs)
else: message(self.owner.name.capitalize() + ' misses ' + target.name + ' completely!', libtcod.lightest_green, gldir.game_msgs)
def heal(self, amount):
self.hp += amount
if self.hp > self.max_hp:
self.hp = self.max_hp
def power(self, multipliers = [1]):
if self.owner is gldir.player:
equipments = get_all_equipped(self.owner)
flat_bonus = 1
equiproll = 0
multiplicative_component = 0
for equip in equipments:
equiproll += equip.roll_dmg()
multiplicative_component += equiproll
combat_flatbonus = gldir.player.ctree.level * 2
flat_bonus += combat_flatbonus
return Dmg(multiplicative_component, product(multipliers), flat_bonus)
else:
return normal_randomize(self.base_power, self.base_power/10)
@property
def armor(self): #return actual defense, by summing up the bonuses from all equipped items
bonus = sum(int(math.ceil(equipment.armor_bonus/2)) for equipment in get_all_equipped(self.owner))
return self.base_armor + bonus
@property
def max_hp(self): #return actual max_hp, by summing up the bonuses from all equipped items
bonus = sum(equipment.max_hp_bonus for equipment in get_all_equipped(self.owner))
return self.base_max_hp + bonus
# exemple: if attackn == 3.4, it does 3 attacks always and has a 40% chance of doing an additional attack for a total of 4
class Dmg:
def __init__(self, multiplicative, multiplier = 1, flat = 0):
self.multiplicative = multiplicative
self.multiplier = multiplier
self.flat = flat
def add(self, *args):
if len(args) == 3:
self.multiplicative += args[0]
self.multiplier *= args[1]
self.flat += args[2]
elif len(args) == 1:
damage = args[0]
if isinstance(damage, Dmg): # if argument is another damage instance, adds them together
self.multiplicative += damage.multiplicative
self.multiplier *= damage.multiplier
self.flat += damage.flat
elif type(damage) == float or type(damage) == int: # if argument is just a number, adds it as multiplicative
self.multiplicative += damage
def resolve(self):
return self.multiplicative * self.multiplier + self.flat
class SpTile:
def __init__(self, name, char = None, foreground = libtcod.white, background = libtcod.black, onwalk_effect = None):
self.name = name#
self.char = char #
self.foreground = foreground #
self.background = background #
self.onwalk_effect = onwalk_effect # sptile is a component, similar to how equipment, items, fighter etc works
# # added to Tile
def apply_onwalk(self, walker): #
if self.onwalk_effect and walker.fighter: #
for effect in self.onwalk_effect: #
if effect == 'damage': walker.fighter.take_damage(self.onwalk_effect['damage']) #
class Tile:
def __init__(self, blocked, block_sight = None, special = None, x = 0, y = 0):
self.blocked = blocked
self.explored = False
self.special = special
self.x = x
self.y = y
#blocks sight by default if blocks movement (standard wall)
if block_sight is None: self.block_sight = blocked
def get_drawing(self):
for drawing in gldir.drawdir.drawinglist:
if self in [tile for tile in drawing.drawntile_list]: #gets the drawing from the chosen tile
wanted_drawing = drawing
return wanted_drawing
class GameObj(object):
def __init__(self, x, y, char, name, color, blocks = False, fighter = None, ai = None, ignore_fov = False, equipment = None, item = None):
self.x = x
self.y = y
self.ai = ai
self.char = char
self.color = color
self.blocks = blocks
self.name = name
self.equipment = equipment
self.item = item
self.ignore_fov = ignore_fov
if self.name in catalog.FULL_INAMELIST: self.get_item_components()
self.fighter = fighter
if self.fighter:
self.fighter.owner = self
self.get_ai_component()
def move_astar(self, target):
#Create a FOV map that has the dimensions of the map
fov = libtcod.map_new(MAP_WIDTH, MAP_HEIGHT)
#Scan the current map each turn and set all the walls as unwalkable
for y1 in range(MAP_HEIGHT):
for x1 in range(MAP_WIDTH):
libtcod.map_set_properties(fov, x1, y1, not gamemap[x1][y1].block_sight, not gamemap[x1][y1].blocked)
#Scan all the objects to see if there are objects that must be navigated around
#Check also that the object isn't self or the target (so that the start and the end points are free)
#The AI class handles the situation if self is next to the target so it will not use this A* function anyway
for obj in gldir.game_objs:
if obj.blocks and obj != self and (obj.x, obj.y) != (target.x, target.y):
#Set the tile as a wall so it must be navigated around
libtcod.map_set_properties(fov, obj.x, obj.y, True, False)
#Allocate a A* path
#The 1.41 is the normal diagonal cost of moving, it can be set as 0.0 if diagonal moves are prohibited
my_path = libtcod.path_new_using_map(fov, 1)
#Compute the path between self's coordinates and the target's coordinates
libtcod.path_compute(my_path, self.x, self.y, target.x, target.y)
#Check if the path exists, and in this case, also the path is shorter than 25 tiles
#The path size matters if you want the monster to use alternative longer paths (for example through other rooms) if for example the player is in a corridor
#It makes sense to keep path size relatively low to keep the monsters from running around the map if there's an alternative path really far away
if not libtcod.path_is_empty(my_path) and libtcod.path_size(my_path) < 25:
#Find the next coordinates in the computed full path
x, y = libtcod.path_walk(my_path, True)
if x or y:
if get_equipped_in_slot('main hand'):
if get_equipped_in_slot('main hand').equiptype == 'polearm' and distance_between(Point(gldir.player.x, gldir.player.y), Point(x, y)) < 2 and not isinstance(self, Player):
chance = get_enchant_value(get_equipped_in_slot('main hand'), 'polearm defense')
if libtcod.random_get_float(0, 0, 1) < chance:
message('You fend the ' + self.name + ' off with your polearm.', libtcod.green, gldir.game_msgs)
return #add agility, strength components here later
if get_equipped_in_slot('main hand').equiptype == 'staff' and get_status_from_name(gldir.player, 'spear staff stance') and distance_between(Point(gldir.player.x, gldir.player.y), Point(x, y)) < 2 and not isinstance(self, Player):
if libtcod.random_get_float(0, 0, 1) < 0.4:
message('You fend the ' + self.name + ' off with your staff.', libtcod.green, gldir.game_msgs)
return
#Set self's coordinates to the next path tile
self.x = x
self.y = y
if gamemap[self.x][self.y].special and gamemap[self.x][self.y].special.onwalk_effect:
gamemap[self.x][self.y].special.apply_onwalk(self)
else:
#Keep the old move function as a backup so that if there are no paths (for example another monster blocks a corridor)
#it will still try to move towards the player (closer to the corridor opening)
self.move_towards(target.x, target.y)
#Delete the path to free memory
libtcod.path_delete(my_path)
def move(self, dx, dy):
if not is_blocked(self.x+dx, self.y+dy):
self.x += dx
self.y += dy
if isinstance(self, Player):
director.update(action = 'move', x1 = self.x-dx, y1 = self.y-dy, x2 = self.x, y2 = self.y)
if gamemap[self.x][self.y].special and gamemap[self.x][self.y].special.onwalk_effect:
gamemap[self.x][self.y].special.apply_onwalk(self)
def in_camera(self):
if camera.x <= self.x <= camera.x2 and camera.y <= self.y <= camera.y2: return True
else: return False
def unblocked_move(self, dx, dy):
self.x += dx
self.y += dy
def draw(self):
if (libtcod.map_is_in_fov(gldir.fov_map, self.x, self.y) or self.ignore_fov):
libtcod.console_set_default_foreground(con, self.color)
libtcod.console_put_char_ex(con, self.camx, self.camy, self.char, self.color, libtcod.black)
def clear(self):
libtcod.console_put_char_ex(con, self.camx, self.camy, ' ', libtcod.white,libtcod.black)
def move_towards(self, target_x, target_y):
#vector from this object to the target, and distance
dx = target_x - self.x
dy = target_y - self.y
distance = math.sqrt(dx ** 2 + dy ** 2)
#normalize it to length 1 (preserving direction), then round it and
#convert to integer so the movement is restricted to the map grid
dx = int(round(dx / distance))
dy = int(round(dy / distance))
self.move(dx, dy)
def distance_to(self, other):
#return the distance to another object
dx = other.x - self.x
dy = other.y - self.y
return math.sqrt(dx ** 2 + dy ** 2)
def distance(self,x,y):
return math.sqrt((x - self.x) ** 2 + (y - self.y) ** 2)
def send_to_back(self):
gldir.game_objs.remove(self)
gldir.game_objs.insert(0, self)
def send_to_front(self):
gldir.game_objs.remove(self)
gldir.game_objs.append(self)
def get_ai_component(self):
if self.name in catalog.FULL_MONSTERLIST:
self.ai = AI.DumbAI(self, gldir)
def get_item_components(self):
if self.name == 'healing salve': #only basic stats go here, for special functions and descriptions go to catalog
self.item = Item(self, weight = 0.5, depth_level = 2, use_function = pot_heal, itemtype = 'salve')
colorchoice = check_colorkeeper(self.name)
elif self.name == 'pipe gun':
self.item = Item(self, weight = 2, depth_level = 2, use_function = consumable_pipegun, itemtype = 'gadget')
colorchoice = check_colorkeeper(self.name)
elif self.name == 'crude grenade':
self.item = Item(self, weight = 1, depth_level = 2, use_function = consumable_crudenade, itemtype = 'gadget')
colorchoice = check_colorkeeper(self.name)
elif self.name == 'scrap metal sword':
self.item = Item(self, weight = 7, depth_level = 2, itemtype = 'equipment')
self.equipment = Equipment(self, slot='main hand', base_dmg = [4,7], equiptype = 'heavy blade')
elif self.name == 'rebar blade':
self.item = Item(self, weight = 20, depth_level = 2,itemtype = 'equipment')
self.equipment = Equipment(self, slot = 'main hand', base_dmg = [8,11], twohand = True, equiptype = 'heavy blade')
elif self.name == 'sharpened stick':
self.item = Item(self, weight = 6, depth_level = 2,itemtype = 'equipment')
self.equipment = Equipment(self, slot = 'main hand', base_dmg = [8,11], equiptype = 'polearm')
elif self.name == 'heavy broomstick':
self.item = Item(self, weight = 10, depth_level = 2,itemtype = 'equipment')
self.equipment = Equipment(self, slot = 'main hand', base_dmg = [6,8], twohand = True, equiptype = 'staff')
elif self.name == 'kitchen knife':
self.item = Item(self, weight = 4, depth_level = 2, itemtype = 'equipment')
self.equipment = Equipment(self, slot='main hand', base_dmg = [3,4], equiptype = 'light blade')
elif self.name == 'baseball bat':
self.item = Item(self, weight = 10, depth_level = 2, itemtype = 'equipment')
self.equipment = Equipment(self, slot='main hand', base_dmg = [4,7], twohand = True, equiptype = 'cudgel')
elif self.name == 'metal plate':
self.item = Item(self, weight = 5, depth_level = 2, itemtype = 'equipment')#weapons need itemtype, but armor can just get a slot check
self.equipment = Equipment(self, slot='off hand', armor_bonus = 3, dodge_bonus = 2, equiptype = 'shield')
elif self.name == 'goat leather sandals':
self.item = Item(self, weight = 2, depth_level = 2, itemtype = 'equipment')
self.equipment = Equipment(self, slot='feet', dodge_bonus = 2, equiptype = 'armor')