-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
14672 lines (13418 loc) · 652 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 colors, math, textwrap, time, os, sys, code, gzip, pathlib, traceback, ffmpy, pdb, copy, random, cProfile, functools #Code is not unused. Importing it allows us to import the rest of our custom modules in the code package.
import tdlib as tdl
import code.dialog as dial
import music as mus
import simpleaudio as sa
import threading, multiprocessing
import dill #THIS IS NOT AN UNUSED IMPORT. Importing this changes the behavior of the pickle module (and the shelve module too), so as we can actually save lambda expressions. EDIT : It might actually be useless to import it here, since we import it in the dilledShelve module, but it freaking finally works perfectly fine so we're not touching this.
from tdlib import *
from random import randint, choice
from math import *
from code.custom_except import *
from copy import copy, deepcopy
from os import makedirs
from collections import deque
from code.constants import MAX_HIGH_CULTIST_MINIONS, ACTION_COSTS
import code.nameGen as nameGen
import code.xpLoaderPy3 as xpL
import code.dunbranches as dBr
import code.dilledShelve as shelve
import code.spellGen as spellGen
from code.dunbranches import gluttonyDungeon
from code.custom_except import *
from music import playWavSound
from multiprocessing import freeze_support, current_process
#import code.chasmGen as chasmGen
#import code.holeGen as holeGen
from code.classes import Tile
import code.newFullMapGen as mapGen
import code.itemGen as itemGen
from tkinter import *
from tkinter.messagebox import * #For making obvious freaking error boxes when the console gets too bloated to read anything useful.
if (__name__ == '__main__' or __name__ == 'main__main__'):
import code.layoutReader as layoutReader
activeProcess = []
def notCloseImmediatelyAfterCrash(exc_type, exc_value, tb):
'''
Does exactly what it says on the tin : prevents the console from closing immediately after crash
'''
traceback.print_exception(exc_type, exc_value, tb) #Print the error message
try:
root.__del__() #Delete the game window
except Exception as error:
print('Cannot delete window')
print('Problem = ' + str(type(error)))
print('Details = ' + str(error.args))
try:
for process in activeProcess:
process.terminate()
except:
print("Couldn't terminate process")
if getattr(sys, 'frozen', False): #If we are running the frozen binaries, then we prevent the console from immediately closing
input('Press Enter to exit') #Prevent stuff from executing further until we press Enter
else:
pass #If we are not running the frozen binaries, we close the program immediately, since we can read the error log in IDLE/PyDev/WhateverIDEYouAreUsing's console.
os._exit(-1) #Exit the program
sys.excepthook = notCloseImmediatelyAfterCrash #We call the above defined function each time the program encounters an unhandled exception. Don't try to change this function to a simple 'pass' so as to 'fix all crashes'. This would make so a lot of stuff would break and we wouldn't know when it did break or what caused it to break.
# Naming conventions :
# MY_CONSTANT
# myVariable
# myFunction()
# MyClass
# Not dramatic if you forget about this (it happens to me too), but it makes reading code easier
class MusicThread(threading.Thread):
def __init__(self, musicName = 'Bumpy_Roots.wav'):
self.musicName = musicName
self.playObj = None
threading.Thread.__init__(self)
self.daemon = True
def run(self):
while True:
if self.playObj is None or not self.playObj.is_playing():
self.playObj = playWavSound(self.musicName, forceStop=True)
def runMusic(musicName):
print('RUNNING MUSIC')
playObj = None
while True:
if playObj is None or not playObj.is_playing():
playObj = playWavSound(musicName, forceStop=True)
class NamedConsole(tdl.Console):
def __init__(self, name, width, height, type = 'noType'):
self.name = name
self.type = type
tdl.Console.__init__(self, width, height)
#_____________ CONSTANTS __________________
MOVEMENT_KEYS = {
#Standard arrows
'UP': [0, -1],
'DOWN': [0, 1],
'LEFT': [-1, 0],
'RIGHT': [1, 0],
# Diagonales (pave numerique off)
'HOME': [-1, -1],
'PAGEUP': [1, -1],
'PAGEDOWN': [1, 1],
'END': [-1, 1],
# Pave numerique
# 7 8 9
# 4 6
# 1 2 3
'KP1': [-1, 1],
'KP2': [0, 1],
'KP3': [1, 1],
'KP4': [-1, 0],
'KP6': [1, 0],
'KP7': [-1, -1],
'KP8': [0, -1],
'KP9': [1, -1],
}
WIDTH, HEIGHT, LIMIT = 159, 80, 20 #Defaults : 150, 80, 20
MAP_WIDTH, MAP_HEIGHT = 140, 60 #Defaults : 140, 60
MID_MAP_WIDTH, MID_MAP_HEIGHT = MAP_WIDTH//2, MAP_HEIGHT//2
MID_WIDTH, MID_HEIGHT = int(WIDTH/2), int(HEIGHT/2)
# - GUI Constants -
BAR_WIDTH = 20 #Default : 20
PANEL_HEIGHT = HEIGHT - MAP_HEIGHT - 1 #Default : 10
PANEL_WIDTH = MAP_WIDTH #default: WIDTH
CON_HEIGHT = HEIGHT - PANEL_HEIGHT
MID_CON_HEIGHT = int(CON_HEIGHT // 2)
PANEL_Y = HEIGHT - PANEL_HEIGHT
LOOK_HEIGHT = PANEL_HEIGHT
LOOK_Y = PANEL_Y
LOOK_WIDTH = 21 #Default: 15
LOOK_X = MAP_WIDTH - LOOK_WIDTH + 1
SIDE_PANEL_WIDTH = WIDTH - MAP_WIDTH #Default: WIDTH - PANEL_WIDTH
SIDE_PANEL_X = MAP_WIDTH
SIDE_PANEL_Y = 0
SIDE_PANEL_MODES = ['enemies', 'items', 'inventory', 'equipment', 'spells', 'buffs', 'stealth']
currentSidepanelMode = 0
SIDE_PANEL_TEXT_WIDTH = SIDE_PANEL_WIDTH - 5
SIDE_PANEL_INFO_Y = 4 #Default: 5
MSG_X = BAR_WIDTH + 9 #Default : BAR_WIDTH + 10
MSG_WIDTH = WIDTH - BAR_WIDTH - 10 - 40 #Default : WIDTH - BAR_WIDTH - 10 - 40
MSG_HEIGHT = PANEL_HEIGHT - 2 #Default : PANEL_HEIGHT - 1
BUFF_WIDTH = 30 #Default : 30
BUFF_X = WIDTH - 35 #Default : WIDTH - 35
INVENTORY_WIDTH = 70 #Default : 70
SPELLS_MENU_WIDTH = INVENTORY_WIDTH + 4 #Default : INVETORY_WIDTH + 4 (so as to compensate for the slightly longer headers).
SPELL_MENU_WIDTH = SPELLS_MENU_WIDTH #Alias for SPELLS_MENU_WIDTH because dumbass me always types one in place of the other.
LEVEL_SCREEN_WIDTH = 40 #Default : 40
CHARACTER_SCREEN_WIDTH = 50 #Default : 50
CHARACTER_SCREEN_HEIGHT = 21 #Default : 21
DEATH_SCREEN_WIDTH = 25 #Default : 25
DEATH_SCREEN_HEIGHT = 10 #Default : 10
consolesDisplayed = False
heroName = None
FORBIDDEN_NAMES = ["Ayeth", "Pukil", "Zarg", "Guillem"]
SURPRISE_ATTACK_CRIT = 30
SPELL_INFO_WIDTH = 60 #Default : 60 / This is actually the width which we pass to textwrap when displaying the spells description (which is useless in normal circumstances), not the actual width of the menubox itself. In other terms, this is the maximum width value that the actual menubox width value can take.
TRAIT_INFO_WIDTH = 25
def getHeroName():
hiddenPath = findHiddenOptionsPath()
if not os.path.exists(hiddenPath):
return None
try:
hOptionsFilePath = os.path.join(hiddenPath, "DATA")
hOptionsFile = open(hOptionsFilePath, "r")
line = hOptionsFile.readline()
splittedLine = line.split(":")
heroName = splittedLine[1]
return heroName
except:
traceback.print_exc()
return None
# - GUI Constants -
# - Consoles -
if (__name__ == '__main__' or __name__ == 'main__main__') and not consolesDisplayed and current_process().name == 'MainProcess':
freeze_support()
print('Displaying consoles because instance is ' + __name__)
root = tdl.init(WIDTH, HEIGHT, 'Dementia')
con = NamedConsole('con', WIDTH, HEIGHT)
panel = NamedConsole('panel', WIDTH, PANEL_HEIGHT)
sidePanel = NamedConsole('side panel', SIDE_PANEL_WIDTH, HEIGHT)
lookPanel = NamedConsole('look panel', LOOK_WIDTH, LOOK_HEIGHT)
consolesDisplayed = True
else:
print(__name__)
root = None
con = None
panel = None
sidePanel = None
lookPanel = None
# - Consoles
FOV_recompute = True
FOV_ALGO = 'BASIC' #Default : BASIC
FOV_LIGHT_WALLS = True
SIGHT_RADIUS = 15 #Default : 10
MAX_ROOM_MONSTERS = 3 #Default : 3
MAX_ROOM_ITEMS = 3 #Default : 3
GRAPHICS = 'modern'
LEVEL_UP_BASE = 200 # Set to 200 once testing complete
LEVEL_UP_FACTOR = 150 #Default : 150
SKILLPOINTS_PER_LEVEL = 2 #Default: 2
NATURAL_REGEN = True
BASE_HIT_CHANCE = 50 #Default : 50
boss_FOV_recompute = True
BOSS_FOV_ALGO = 'BASIC' #Default : BASIC
BOSS_SIGHT_RADIUS = 20 #Default : 20
bossDungeonsAppeared = {'gluttony': False, 'greed' : False, 'wrath': False}
lastHitter = None
nemesisList = []
mobsToCalculate = []
mustCalculate = False
currentMusic = 'No_Music.wav'
detectedPlayerThisTurn = []
monstersDetected = [[],[],[],[],[]]
exploredMaps = {} #template: exploredMaps = {'main1': [(x, y, character, blocked, chasm),...], 'main1stairs': [(x, y, char, color)]}
tutorial = False
hasSpokenToGeneral = False
# - Spells -
LIGHTNING_DAMAGE = 40 #Default : 40
LIGHTNING_RANGE = 5 #Default : 5
CONFUSE_NUMBER_TURNS = 10 #Default : 10
CONFUSE_RANGE = 8 #Default: 8
DARK_PACT_DAMAGE = 24 #Default : 24
FIREBALL_SPELL_BASE_DAMAGE = 12 #Default : 12
FIREBALL_SPELL_BASE_RADIUS = 1 #Default : 1
FIREBALL_SPELL_BASE_RANGE = 4 #Default : 4
RESURECTABLE_CORPSES = ["darksoul", "ogre"]
BASE_HUNGER = 1500 #Default : 500
CRITICAL_MULTIPLIER = 3 #Default : 3
MAX_ASTAR_FAILS = 1 #Possibly unstable at 1 (but best performance), if you get weird results with Astar (aside from freezing) try bumping this number up a LITTLE bit (3 is already way overkill)
REGEN_THRESHOLD = 4000 #Number of iterations of stairs placing loop before you throw away current map and regenerates another one. Setting this too high may make map generation longer. Setting this too low may provoke infinite loops or cause the game to reject potentially valid maps (also making the map gen longer). (base : 2000)
# - Spells -
#_____________ CONSTANTS __________________
myMap = None
color_dark_wall = dBr.mainDungeon.mapGeneration['wallDarkFG']
color_light_wall = dBr.mainDungeon.mapGeneration['wallFG']
color_dark_ground = dBr.mainDungeon.mapGeneration['groundDarkBG']
color_dark_gravel = dBr.mainDungeon.mapGeneration['gravelDarkFG']
color_light_ground = dBr.mainDungeon.mapGeneration['groundBG']
color_light_gravel = dBr.mainDungeon.mapGeneration['gravelFG']
maxRooms = dBr.mainDungeon.maxRooms
roomMinSize = dBr.mainDungeon.roomMinSize
roomMaxSize = dBr.mainDungeon.roomMaxSize
gameState = 'playing'
playerAction = None
DEBUG = False #If true, enables debug messages
REVEL = False #If true, revels all items
drawDjik = False
stopBossFF = False
lookCursor = None
cursor = None
bossTiles = None
bossEntrance = None
gameMsgs = [] #List of game messages
logMsgs = []
tilesInRange = []
showTilesInRange = False
explodingTiles = []
tilesinPath = []
tilesInRect = []
menuWindows = []
hiroshimanNumber = 0
FOV_recompute = True
inventory = [] #Player inventory
equipmentList = [] #Player equipment
identifiedItems = []
activeSounds = []
spells = [] #List of all spells in the game
djikVisitedTiles = []
markers = []
visuBoss = []
########
# These need to be globals because otherwise Python will flip out when we try to look for some kind of stairs in the object lists.
stairs = None
upStairs = None
gluttonyStairs = None
townStairs = None
greedStairs = None
wrathStairs = None
########
hiroshimanHasAppeared = False
highCultistHasAppeared = False
player = None
levelAttributes = None
currentBranch = dBr.mainDungeon #Setting this to None causes errors. It doesn't matter tough, since this gets updated on loading or starting a game.
branchLevel = 1
totalLevel = 1
depthLevel = 1
def findCurrentDir():
if getattr(sys, 'frozen', False):
datadir = os.path.dirname(sys.executable)
else:
datadir = os.path.dirname(__file__)
return datadir
def deleteSaves():
if not os.path.isdir(absDirPath):
os.makedirs(absDirPath)
print('Created save folder')
os.chdir(absDirPath)
saves = [save for save in os.listdir(absDirPath) if ((save.endswith(".bak") or save.endswith(".dat") or save.endswith(".dir") or save.startswith("map")) and not save.startswith('nemesis'))]
for save in saves:
os.remove(save)
print("Deleted " + str(save))
curDir = findCurrentDir()
relDirPath = "save"
relPath = os.path.join("save", "savegame")
relPicklePath = os.path.join("save", "equipment")
relAssetPath = "assets"
relSoundPath = os.path.join("assets", "sound")
relAsciiPath = os.path.join("assets", "ascii")
relMusicPath = os.path.join("assets", "music")
relMetaPath = os.path.join("metasave", "meta")
relMetaDirPath = "metasave"
relCodePath = "code"
absDirPath = os.path.join(curDir, relDirPath)
absFilePath = os.path.join(curDir, relPath)
absPicklePath = os.path.join(curDir, relPicklePath)
absAssetPath = os.path.join(curDir, relAssetPath)
absSoundPath = os.path.join(curDir, relSoundPath)
absMusicPath = os.path.join(curDir, relMusicPath)
absAsciiPath = os.path.join(curDir, relAsciiPath)
absMetaPath = os.path.join(curDir, relMetaPath)
absMetaDirPath = os.path.join(curDir, relMetaDirPath)
absCodePath = os.path.join(curDir, relCodePath)
stairCooldown = 0
pathfinder = None
pathToTargetTile = []
def convertMusics():
musicList = ['Bumpy_Roots', 'Dusty_Feelings', 'Hoxton_Princess', 'Sweltering_Battle']
tryPath = os.path.join(absCodePath, 'ffmpeg.exe')
if os.path.exists(tryPath):
executablePath = os.path.join(absCodePath, 'ffmpeg.exe')
else:
executablePath = os.path.join(curDir, 'ffmpeg.exe')
for music in musicList:
mp3Music = music + '.mp3'
wavMusic = music + '.wav'
mp3Path = os.path.join(absMusicPath, mp3Music)
wavPath = os.path.join(absSoundPath, wavMusic)
if os.path.exists(wavPath):
print('MUSIC_CHK : Found {}'.format(wavPath))
else:
print('MUSIC_CHK_WAR : Didnt found {}'.format(wavPath))
if os.path.exists(mp3Path):
print('MUSIC_CONV : Converting {} to wav'.format(mp3Path))
if sys.platform.startswith('win32') or sys.platform.startswith('win64'):
ff = ffmpy.FFmpeg(inputs = {mp3Path : None}, outputs= {wavPath : None}, executable= executablePath)
else:
ff = ffmpy.FFmpeg(inputs = {mp3Path : None}, outputs= {wavPath : None})
ff.run()
print('MUSIC_CONV : Created {}'.format(wavPath))
else:
print('MUSIC_CONV_ERR : Path {} doesnt exists, skipping...'.format(mp3Path))
print()
def animStep(waitTime = .125, doUpdate = True):
global FOV_recompute
FOV_recompute = True
if doUpdate:
Update()
tdl.flush()
time.sleep(waitTime)
#_____________MENU_______________
def drawMenuOptions(y, options, window, page, width, height, headerWrapped, maxPages, pagesDisp, selectedIndex, noItemMessage = None, displayItem = False):
window.clear()
for i, line in enumerate(headerWrapped):
window.draw_str(1, 1+i, headerWrapped[i], fg = colors.amber)
if pagesDisp:
window.draw_str(10, y - 2, str(page + 1) + '/' + str(maxPages + 1), fg = colors.amber)
letterIndex = ord('a')
counter = 0
pageIndex = 0
for k in range(width):
window.draw_char(k, 0, chr(196))
window.draw_char(0, 0, chr(218))
window.draw_char(k, 0, chr(191))
kMax = k
for l in range(height):
if l > 0:
window.draw_char(0, l, chr(179))
window.draw_char(kMax, l, chr(179))
lMax = l
for m in range(width):
window.draw_char(m, lMax, chr(196))
window.draw_char(0, lMax, chr(192))
window.draw_char(kMax, lMax, chr(217))
if (noItemMessage is None or not options or options[0] != str(noItemMessage)):
if len(options) == 1:
print(options[0])
print(str(noItemMessage))
for optionText in options:
if counter >= page * 26 and counter < (page + 1) * 26:
text = '(' + chr(letterIndex) + ') ' + optionText
if selectedIndex == pageIndex:
window.draw_str(1, y, text, fg = colors.black, bg = colors.white)
else:
window.draw_str(1, y, text, bg=None)
letterIndex += 1
y += 1
pageIndex += 1
counter += 1
else:
window.draw_str(1, y, options[0], bg = None, fg = colors.red)
if displayItem:
print('displaying item')
x = MID_WIDTH - int(width/2) - 15
else:
print('not displaying item')
x = MID_WIDTH - int(width/2)
y = MID_HEIGHT - int(height/2)
root.blit(window, x, y, width, height, 0, 0)
if not displayItem:
tdl.flush()
def menu(header, options, width, usedList = None, noItemMessage = None, inGame = True, adjustHeight = True, needsInput = True, displayItem = False, name = 'noName', switchKey = None, switchHeader = None):
global menuWindows, FOV_recompute
hasSwitched = False
index = 0
print('display item:', str(displayItem))
page = 0
pagesDisp = True
maxPages = len(options)//26
if maxPages < 1:
pagesDisp = False
pagesDispHeight = 0
if pagesDisp:
pagesDispHeight = 1
headerWrapped = textwrap.wrap(header, width)
headerHeight = len(headerWrapped)
if switchHeader :
switchHeaderWrapped = textwrap.wrap(switchHeader, width)
switchHeaderHeight = len(switchHeaderWrapped)
if adjustHeight:
toAdd = 3
else:
toAdd = 2
if header == "":
headerHeight = 0
if len(options) > 26:
height = 26 + headerHeight + toAdd + pagesDispHeight
else:
height = len(options) + headerHeight + toAdd + pagesDispHeight
if menuWindows and inGame:
for mWindow in menuWindows:
mWindow.clear()
window = NamedConsole(name, width, height, 'menu')
menuWindows.append(window)
window.draw_rect(0, 0, width, height, None, fg=colors.white, bg=None)
if not hasSwitched:
y = headerHeight + 2 + pagesDispHeight
headerToDraw = headerWrapped
else:
y = switchHeaderHeight + 2 + pagesDispHeight
headerToDraw = switchHeaderWrapped
drawMenuOptions(y, options, window, page, width, height, headerToDraw, maxPages, pagesDisp, index, noItemMessage, displayItem)
print('Not loop menu option draw')
if displayItem and usedList:
item = usedList[0].Item
item.displayItem(posX = MID_WIDTH + width//2 - 15)
print('Not loop item disp')
tdl.flush()
if needsInput:
choseOrQuit = False
index = 0
while not choseOrQuit:
if not hasSwitched:
y = headerHeight + 2 + pagesDispHeight
headerToDraw = headerWrapped
else:
y = switchHeaderHeight + 2 + pagesDispHeight
headerToDraw = switchHeaderWrapped
if page == maxPages:
maxIndex = len(options) - maxPages * 26 - 1
else:
maxIndex = 25
#choseOrQuit = True
arrow = False
drawMenuOptions(y, options, window, page, width, height, headerToDraw, maxPages, pagesDisp, index, noItemMessage, displayItem)
tdl.flush()
print('Loop menu option disp')
key = tdl.event.key_wait_no_shift()
keyChar = key.keychar
if keyChar == '':
keyChar = ' '
elif keyChar == 'RIGHT':
if pagesDisp:
index = 0
page += 1
choseOrQuit = False
arrow = True
elif keyChar == 'LEFT':
if pagesDisp:
index = 0
page -= 1
choseOrQuit = False
arrow = True
elif keyChar == 'UP':
choseOrQuit = False
index -= 1
arrow = True
elif keyChar == 'DOWN':
choseOrQuit = False
index += 1
arrow = True
if page > maxPages:
page = 0
if page < 0:
page = maxPages
if index < 0:
index = maxIndex
if index > maxIndex:
index = 0
if displayItem and usedList:
item = usedList[index + page * 26].Item
item.displayItem(posX = MID_WIDTH + width//2 - 15)
print('Loop item disp')
if not arrow:
if switchKey and keyChar == switchKey:
hasSwitched = not hasSwitched
for loop in range(10):
print("SWITCHED")
if keyChar in 'abcdefghijklmnopqrstuvwxyz':
if DEBUG:
message(keyChar)
index = ord(keyChar) - ord('a')
if index >= 0 and index < len(options):
if not switchKey:
return index + page * 26
else:
return (index + page * 26, hasSwitched)
elif keyChar.upper() == 'ENTER':
if menuWindows and inGame:
for mWindow in menuWindows:
mWindow.clear()
ind = menuWindows.index(mWindow)
del menuWindows[ind]
if not switchKey:
return index + page * 26
else:
return (index + page * 26, hasSwitched)
elif keyChar.upper() == "ESCAPE":
print('Cancelled')
if not switchKey:
return "cancelled"
else:
return ("cancelled", False)
else:
continue
else:
pass
if not switchKey:
return None
else:
return (None, False)
def msgBox(text, width = 50, inGame = True, adjustHeight = True, adjustWidth = False, needsInput = True):
if adjustWidth:
textLength = len(text)
width = textLength + 2
menu(text, [], width, None, inGame, adjustHeight, needsInput)
def drawCentered(cons = con , y = 1, text = "Lorem Ipsum", fg = None, bg = None):
xCentered = (WIDTH - len(text))//2
cons.draw_str(xCentered, y, text, fg, bg)
def drawCenteredVariableWidth(cons, y, text, fg = None, bg = None, width = WIDTH):
xCentered = (width - len(text))//2
cons.draw_str(xCentered, y, text, fg, bg)
def getCenterFilled(text = 'Lorem Ipsum'):
xCentered = (WIDTH - len(text))//2
newText = ''
passNb = 0
while passNb != 2:
for x in range(xCentered):
newText += ' '
if passNb == 0:
newText += text
passNb += 1
return newText
def getRightFilled(text = 'Lorem Ipsum'):
newText = str(text)
remaining = WIDTH - len(newText)
for loop in range(remaining):
newText += ' '
return newText
def drawCenteredOnX(cons = con, x = 1, y = 1, text = "Lorem Ipsum", fg = None, bg = None):
centeredOnX = x - (len(text)//2)
cons.draw_str(centeredOnX, y, text, fg, bg)
def message(newMsg, color = colors.white):
newMsgLines = textwrap.wrap(newMsg, MSG_WIDTH) #If message exceeds log width, split it into two or more lines
for line in newMsgLines:
if len(gameMsgs) == MSG_HEIGHT:
del gameMsgs[0] #Deletes the oldest message if the log is full
gameMsgs.append((line, color))
logMsgs.append((line, color))
#_____________MENU_______________
#_________ BUFFS ___________
def convertBuffsToNames(fighter):
names = []
for buff in fighter.buffList:
names.append(buff.name)
return names
def convertTilesToCoords(tilesList):
newList = []
for tile in tilesList:
newList.append((tile.x, tile.y))
return newList
def consumeRessource(fighter, buff, ressources = {'stamina': 1}):
ressourcelist = list(ressources.keys())
for ressource in ressourcelist:
if ressource == 'stamina':
fighter.stamina -= ressources[ressource]
if fighter.stamina <= 0:
fighter.stamina = 0
buff.removeBuff()
if ressource == 'MP':
fighter.MP -= ressources[ressource]
if fighter.MP <= 0:
fighter.MP = 0
buff.removeBuff()
if ressource == 'HP':
fighter.hp -= ressources[ressource]
if fighter.hp <= 0:
fighter.hp = 0
buff.removeBuff()
def randomDamage(name, fighter = None, chance = 33, minDamage = 1, maxDamage = 1, dmgMessage = None, dmgColor = colors.red, msgPlayerOnly = True, dmgType = {'fire': 100}):
dice = randint(1, 100)
if dice <= chance:
damage = randint(minDamage, maxDamage)
damageDict = {}
keyList = list(dmgType.keys())
i = 0
for key in keyList:
if i == len(keyList)-1:
dmgList = [damageDict[dmgKey] for dmgKey in keyList if dmgKey != key]
damageDict[key] = damage - sum(dmg for dmg in dmgList)
else:
damageDict[key] = round((dmgType[key] * damage)/100)
i += 1
damageTaken = fighter.takeDamage(damageDict, name)
totalDmg = 0
for key in list(damageTaken.keys()):
totalDmg += damageTaken[key]
if (dmgMessage is not None) and (fighter == player.Fighter or (not msgPlayerOnly)):
message(dmgMessage.format(totalDmg), dmgColor)
def addSlot(fighter, slot):
print('adding {} slot to {}'.format(slot, fighter.owner.name))
fighter.slots.append(slot)
class Buff: #also (and mainly) used for debuffs
def __init__(self, name, color, owner = None, cooldown = 20, showCooldown = True, showBuff = True,
applyFunction = None, continuousFunction = None, removeFunction = None,
strength = 0, dexterity = 0, constitution = 0, willpower = 0, hp = 0, armor = 0, power = 0, accuracy = 0, evasion = 0, maxMP = 0,
critical = 0, armorPenetration = 0, rangedPower = 0, stamina = 0, stealth = 0, attackSpeed = 0, moveSpeed = 0, rangedSpeed = 0,
resistances = {'physical': 0, 'poison': 0, 'fire': 0, 'cold': 0, 'lightning': 0, 'light': 0, 'dark': 0, 'none': 0},
attackTypes = {}, flight = None):
'''
Function used to initialize a new instance of the Buff class
'''
self.name = name
self.color = color
self.baseCooldown = cooldown
self.curCooldown = cooldown
self.applyFunction = applyFunction
self.continuousFunction = continuousFunction
self.removeFunction = removeFunction
self.owner = owner
self.showCooldown = showCooldown
self.showBuff = showBuff
self.strength = strength
self.dexterity = dexterity
self.constitution = constitution
self.willpower = willpower
self.maxHP = hp
self.armor = armor
self.power = power
self.accuracy = accuracy
self.evasion = evasion
self.maxMP = maxMP
self.critical = critical
self.armorPenetration = armorPenetration
self.rangedPower = rangedPower
self.stamina = stamina
self.stealth = stealth
self.attackSpeed = attackSpeed
self.moveSpeed = moveSpeed
self.rangedSpeed = rangedSpeed
self.resistances = resistances
self.attackTypes = attackTypes
self.flight = flight
self.hpDiff = 0
self.mpDiff = 0
def applyBuff(self, target):
'''
Method allowing to apply the buff to target creature
'''
print(self.name, target.name)
self.owner = target
if not self.name in convertBuffsToNames(target.Fighter): #If target is not already under effect of the buff
self.curCooldown = self.baseCooldown #Initialization of the buff cooldown
if self.showBuff:
message(self.owner.name.capitalize() + ' is now ' + self.name + '!', self.color) #If it is necessary, inform the player of the buff
if self.applyFunction is not None:
self.applyFunction(self.owner.Fighter) #If the applyFunction method exists, execute it
self.owner.Fighter.buffList.append(self) #Add the buff to target's buffs list
self.owner.Fighter.hp += self.maxHP
self.owner.Fighter.MP += self.maxMP
else: #If target is already under effect of the buff
bIndex = convertBuffsToNames(self.owner.Fighter).index(self.name)
target.Fighter.buffList[bIndex].curCooldown += self.baseCooldown #Extend duration of the buff
def removeBuff(self):
'''
Method allowing to remove the buff from target creature
'''
if self.removeFunction is not None: #If removeFunction method exists, execute it
self.removeFunction(self.owner.Fighter)
self.owner.Fighter.buffList.remove(self) #Delete the buff from target creature's buffs list
if self.owner.Fighter.buffList is None:
self.owner.Fighter.buffList = []
if self.showBuff:
message(self.owner.name.capitalize() + ' is no longer ' + self.name + '.', self.color) #Inform the player
def passTurn(self):
'''
Method called each turn
'''
self.curCooldown -= 1 #Decrease from 1 the buff cooldown
if self.curCooldown <= 0: #If buff reached its time, call the removeBuff method
self.removeBuff()
else: #If buff has not yet reached its time limit, we call the continuousFunction if it exists
if self.continuousFunction is not None:
self.continuousFunction(self.owner.Fighter)
class TileBuff:
def __init__(self, name, fg = None, bg = None, char = None, owner = None, cooldown = 20, blocksTile = False, buffsWhenWalked=[]):
self.name = name
self.fg = fg
self.bg = bg
self.char = char
self.owner = owner
self.baseCooldown = cooldown
self.curCooldown = cooldown
self.blocksTile = blocksTile
self.buffsWhenWalked = buffsWhenWalked
def applyTileBuff(self, x, y):
global myMap
if myMap[x][y].buffList:
myMap[x][y].buffList.append(self)
else:
myMap[x][y].buffList = [self]
self.owner = myMap[x][y]
def passTurn(self):
self.curCooldown -= 1
if self.curCooldown <= 0:
self.owner.buffList.remove(self)
#_________ BUFFS ___________
#_____________SPELLS_____________
class Spell:
"Class used by all active abilites (not just spells)"
def __init__(self, ressourceCost, cooldown, useFunction, name, ressource = 'MP', type = 'Magic', magicLevel = 0, arg1 = None, arg2 = None, arg3 = None, hiddenName = None, onRecoverLearn = [], castSpeed = 100, template = None):
self.ressource = ressource
self.ressourceCost = ressourceCost
self.maxCooldown = cooldown
self.curCooldown = 0
self.useFunction = useFunction
self.name = name
self.type = type
self.magicLevel = magicLevel
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
if hiddenName:
self.hiddenName = hiddenName
else:
self.hiddenName = name
self.onRecoverLearn = onRecoverLearn
self.castSpeed = castSpeed
self.template = template
def updateSpellStats(self):
if self.name == 'Fireball':
self.arg1 = FIREBALL_SPELL_BASE_RADIUS + player.Player.getTrait('skill', 'Magic ').amount
self.arg2 = FIREBALL_SPELL_BASE_DAMAGE * player.Player.getTrait('skill', 'Magic ').amount
self.arg3 = FIREBALL_SPELL_BASE_RANGE + player.Player.getTrait('skill', 'Magic ').amount
def cast(self, caster = player, target = player):
global FOV_recompute
if caster == player:
self.updateSpellStats()
if self.ressource == 'MP' and caster.Fighter.MP < self.ressourceCost:
FOV_recompute = True
message(caster.name.capitalize() + ' does not have enough MP to cast ' + self.name +'.')
return 'cancelled'
if self.ressource == 'Stamina' and caster.Fighter.stamina < self.ressourceCost:
FOV_recompute = True
message(caster.name.capitalize() + ' does not have enough stamina to cast ' + self.name +'.')
return 'cancelled'
if self.arg1 is None:
if self.useFunction(caster, target) != 'cancelled':
caster.Fighter.actionPoints -= self.castSpeed
FOV_recompute = True
self.setOnCooldown(caster.Fighter)
if self.ressource == 'MP':
caster.Fighter.MP -= self.ressourceCost
elif self.ressource == 'HP':
caster.Fighter.takeDamage({'none': self.ressourceCost}, 'your spell')
elif self.ressource == 'Stamina':
caster.Fighter.stamina -= self.ressourceCost
return 'used'
else:
return 'cancelled'
elif self.arg2 is None and self.arg1 is not None:
if self.useFunction(self.arg1, caster, target) != 'cancelled':
caster.Fighter.actionPoints -= self.castSpeed
FOV_recompute = True
self.setOnCooldown(caster.Fighter)
if self.ressource == 'MP':
caster.Fighter.MP -= self.ressourceCost
elif self.ressource == 'HP':
caster.Fighter.takeDamage({'none': self.ressourceCost}, 'your spell')
elif self.ressource == 'Stamina':
caster.Fighter.stamina -= self.ressourceCost
return 'used'
else:
return 'cancelled'
elif self.arg3 is None and self.arg2 is not None:
if self.useFunction(self.arg1, self.arg2, caster, target) != 'cancelled':
caster.Fighter.actionPoints -= self.castSpeed
FOV_recompute = True
self.setOnCooldown(caster.Fighter)
if self.ressource == 'MP':
caster.Fighter.MP -= self.ressourceCost
elif self.ressource == 'HP':
caster.Fighter.takeDamage({'none': self.ressourceCost}, 'your spell')
elif self.ressource == 'Stamina':
caster.Fighter.stamina -= self.ressourceCost
return 'used'
else:
return 'cancelled'
elif self.arg3 is not None:
if self.useFunction(self.arg1, self.arg2, self.arg3, caster, target) != 'cancelled':
caster.Fighter.actionPoints -= self.castSpeed
FOV_recompute = True
self.setOnCooldown(caster.Fighter)
if self.ressource == 'MP':
caster.Fighter.MP -= self.ressourceCost
elif self.ressource == 'HP':
caster.Fighter.takeDamage({'none': self.ressourceCost}, 'your spell')
elif self.ressource == 'Stamina':
caster.Fighter.stamina -= self.ressourceCost
return 'used'
else:
return 'cancelled'
def setOnCooldown(self, fighter):
try:
fighter.knownSpells.remove(self)
self.curCooldown = self.maxCooldown
fighter.spellsOnCooldown.append(self)
except ValueError:
print('SPELL {} is not in known spell list when trying to set it on cooldown'.format(self.name))
def displayInfo(self):
global FOV_recompute
FOV_recompute = True
if self.template:
baseWidth = SPELL_INFO_WIDTH
desc = dial.formatText(str(self.template), baseWidth)
prevLine = None
descriptionHeight = 0
for line in desc:
if line != "BREAK":
descriptionHeight += 1
else:
if prevLine and prevLine == "BREAK":
descriptionHeight += 1
prevLine = line
height = descriptionHeight + 5
curMaxWidth = 0
for line in desc:
if len(line) > curMaxWidth:
curMaxWidth = len(line)
width = curMaxWidth + 3
if menuWindows:
for mWindow in menuWindows:
if not mWindow.name == 'inventory' and not mWindow.type == 'menu':
mWindow.clear()
print('CLEARED {} WINDOW OF TYPE {}'.format(mWindow.name, mWindow.type))
if mWindow.name == 'displayItemInInventory':
ind = menuWindows.index(mWindow)
del menuWindows[ind]
print('Deleted')
tdl.flush()
FOV_recompute = True
#Update()
window = NamedConsole('displayItemInInventory', width, height)
print('Created disp window')
window.clear()
menuWindows.append(window)
for k in range(width):
window.draw_char(k, 0, chr(196))
window.draw_char(0, 0, chr(218))
window.draw_char(k, 0, chr(191))
kMax = k
for l in range(height):
if l > 0:
window.draw_char(0, l, chr(179))
window.draw_char(kMax, l, chr(179))
lMax = l
for m in range(width):
window.draw_char(m, lMax, chr(196))
window.draw_char(0, lMax, chr(192))
window.draw_char(kMax, lMax, chr(217))
Y = 3
X = 3
prevLine = None
drawCenteredVariableWidth(window, y=1, text = self.name.capitalize(), fg=colors.amber, width=width)
for line in desc:
if line != "BREAK":
window.draw_str(1,Y, line)
incrementY = True