-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
2982 lines (2538 loc) · 105 KB
/
tools.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
"""
This is the main 'bulk' of the game. It has most of the back-end stuff.
Feel free to browse through to see how I did everything!
Don't 'touch' anything please?
"""
#To randomly generate rooms
from random import randint
from os import system #To talk to the 'system'
from functools import reduce #Reduce list -> single value
from platform import system as get_system #To see what system this is
from time import time
from time import sleep
#Takes the raw information for a save file, and a password and encrypts it w/ password
def encrypt_save(password, info):
#Make the information into a set of integers
info = [ord(char) for char in str(info)]
#Make the password into a set of integers
password = [ord(char) for char in password]
#Encrypted information, has to stay as a bunch of numbers
result = []
i = 0 #Stupid iterator variable
for char in info: #Goes through ascii val of a number and encrypts it
#If we go over the last part of the 'key', loop back to the start of it
if i == len(password): i = 0
#Adds that one value part of the key
char += password[i]
#then divides by the length, fully scrambling it
char /= len(password)
#Add result
result.append(char)
#Go onto next part of the key
i += 1
#Return the encrypted result
return result
#Uses the password, and list of numbers (the encrypted information)
# and decrypts it and returns the result
def decrypt_save(password, info):
#Makes the password into a list of numbers
password = [ord(char) for char in password]
#Resulting decrypted stuff
result = []
i = 0 #Stupid iterator variable
for char in info: #Go through every number and decrypt it
if i == len(password): i = 0 #Loop back to first value in key
#Multiply by password length to get closer to original number
char *= len(password)
#Subtract individual value in key to get back to original value
char -= password[i]
#Add the resulting character
try:
result.append(chr(int(char)))
#If an error occurs, then the file hasn't been decoded correctly
except:
result.append("_")
#Move onto next value
i += 1
#The decrypted information
original_info = ""
for char in result:
original_info += char
return original_info #Return original information
#This will take in a password, and checks to see if the password would correctly
# encrypt / decrypt the given information. If it doesn't 'cooperate', then
# we should tell the user to pick a new password
# RETURNS 'TRUE' if password works, 'FALSE' otherwise
def check_password(password):
#Return false, a password can't be nothing
if password == "": return False
#The test information, used to see if the password will work
test = {'name':"Jimbo", "floor":9271, "time":47,
'health potions':15, 'mobs':{1:('zombie', (5, 9), 6, 40, 32),
2:('minotaur', (0, 4), 8, 26, 12), 3:('ker', (7, 2), 6, 5, 99)},
'objects':{1:('priest', (18, 7))},
#If this is even one character off, then it won't work
'final':"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()~`-_=+\\|]}[{'\";:/?.>,<"}
#Turn it into a string for comparison
test = str(test)
#Encrypts, then decrypts the information with the password, this
# is so we can test to see if this password will work for encryption and decryption
encoded_decoded_result = decrypt_save(password, encrypt_save(password, test))
#If the encoded (then decoded) string is exactly the same as
# the starting information, then this password should work fine
if test == encoded_decoded_result:
return True
#If the password failed in decrypting the info..
# then tell the user that this can't be used as a password
return False
#This checks to see if the saves file and highscore file exists.
# if they do, then we're fine, otherwise, make them
def check_highscore_saves():
#If the saves file doesn't exist, then make it
try:
FILE = open('DownwardDescent_Saves.txt', 'r').read()
except FileNotFoundError:
FILE = open('DownwardDescent_Saves.txt', 'w')
FILE.write("{}")
FILE.close()
#If the highscore file doesn't exist, then make it
try:
FILE = open('DownwardDescent_Highscore.txt', 'r').read()
except FileNotFoundError:
FILE = open('DownwardDescent_Highscore.txt', 'w')
start_highscore = "('none', 0)" #Initial high score
#Encrypt it
encrypted_highscore = encrypt_save("DownwardDescent", start_highscore)
FILE.write(str(encrypted_highscore)) #Write in highscore
FILE.close()
#Generates random number
rand = lambda MIN, MAX: randint(MIN, MAX)
#The function used to get 1 char input from character
#If the system is windows.. return relevent getch function
def mk_GETCH():
if get_system() == "Windows":
from msvcrt import getch
return (lambda: getch().decode('utf-8'))
#If the system is instead Linux
elif get_system() == "Linux":
import sys, tty, termios
#The getch function for linux
def GETCH_FUNCTION():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return GETCH_FUNCTION
#Gets single character from user (without enter being pressed)
Getch = mk_GETCH()
#Just waits for input from the user
def pause():
try:
Getch()
except:
pass
#Makes clear function so it works on Linux + Windows
def mk_CLEAR():
#Use the 'cls' command to clear the screen
# if the system is Windows
if get_system() == "Windows":
return (lambda: system('cls'))
#Use the 'clear' command to clear the screen
# if the system is a Linux System
elif get_system() == "Linux":
return (lambda: system('clear'))
#Clears the screen
clear = mk_CLEAR()
#'Rolls' a d20 to see if the player (or anything else)
# can get past the armor class of the other thing
d20_roll = lambda: randint(1, 20)
#'Rolls' a d5 (for randomly getting a health potion)
d5_roll = lambda: randint(1, 5)
#Applies a function f to every value in x
map = lambda f, x: [f(y) for y in x]
#For a list of booleans, uses or on all values
Or = lambda lst: reduce(lambda x,y: x or y, lst)
#Makes a room, h and w are Height and Width
def mk_room(h, w):
new_room = [[]] * h #Make a list of 'h' tall room
i = 0
for line in new_room:
new_room[i] = ['.'] * w #make each room 'w' wide
i += 1
#Adds walls + 'celing' and 'floor'
new_room = [['|']+x+['|'] for x in new_room]
return [[' ']+['_']*w+[' ']]+new_room+[[' ']+['-']*w+[' ']]
#prints out returned dialog (like if the player missed)
def draw_dialog(lst):
for line in lst:
print(line)
#Randomly generates the room
def gen_room():
#The random height and width of the new room
height = randint(3, 10)
width = randint(2, 20)
#Makes the room
return mk_room(height, width)
#Gets the middle-most position of the user
user_pos_setup = lambda ROOM: (len(ROOM[0])//2, len(ROOM)//2)
#Sets up the player for the room
def character_setup():
R = gen_room() #Makes the room
pos = user_pos_setup(R) #Position of player
return R, pos
#Draws the new frame of the room
def draw_room(space):
#Draws room
for line in space: #Go through every line
x = "" #The entire line
for char in line: #Collect the line
x += char
print(x) #Print line
#Return's true on if the space above is a ceiling (another wall)
def ceiling_above(obj_pos, space):
#The tile just above the character
above_tile = space[obj_pos[1]-1][obj_pos[0]]
#Immovable objects (includes enemies)
immovables = ['_', '-', '|', 'Z', 'M', 'K', 'N', 'B', '#', 'S', 'P']
#If the tile above is not an immovable obejct
if not above_tile in immovables:
return False
return True
#Returns true if a floor/ceiling is below the character
def floor_below(obj_pos, space):
#The tile below the character
below_tile = space[obj_pos[1]+1][obj_pos[0]]
#Immovable objects (includes enemies)
immovables = ['_', '-', '|', 'Z', 'M', 'K', 'N', 'B', '#', 'S', 'P']
#Checks if an immovable object is below
if not below_tile in immovables:
return False
return True
#Returns a true if there is a wall to the right of the player
def wall_right(obj_pos, space):
#The tile to the right of the player
right_tile = space[obj_pos[1]][obj_pos[0]+1]
#Immovable objects (includes enemies)
immovables = ['_', '-', '|', 'Z', 'M', 'K', 'N', 'B', '#', 'S', 'P']
#Checks if an obstacle is to the right of the player
if not right_tile in immovables:
return False
return True
#Returns true if there is a wall to the left of the player
def wall_left(obj_pos, space):
#The tile to the left of the user
left_tile = space[obj_pos[1]][obj_pos[0]-1]
#Immovable objects (includes enemies)
immovables = ['_', '-', '|', 'Z', 'M', 'K', 'N', 'B', '#', 'S', 'P']
#Checks if any wall tile is to the left of the player
if not left_tile in immovables:
return False
return True
#Returns a list of all of the spaces around the player
spaces_around_player = lambda pos: [(pos[0]-1, pos[1]), (pos[0]+1, pos[1]), (pos[0], pos[1]-1), (pos[0], pos[1]+1)]
#This returns the mobs that are in position for
# the player to attack them
def get_enemies_in_attack_area(mobs, player_pos):
#Gets all of the areas around the player
areas = spaces_around_player(player_pos)
mob_list = [] #List of mobs in range
for mob_index in mobs:
#Gets the version of the mob
current_mob = mobs[mob_index]
#If the mob's position is any of the areas around the player
# then we should keep track of the index of the mob (etc).
if current_mob.pos in areas:
mob_list.append((mob_index, current_mob))
#Now return those values- of the index- of the monsters around them
return mob_list
#Gives a list of all of the chests around the player
def chests_in_area(objs, player_pos):
#Get all of the areas around the player
areas = spaces_around_player(player_pos)
chest_list = [] #Get all of the chests around player
for chest_index in objs:
#If the chest is in one of the areas
# around the player
if objs[chest_index].pos in areas:
chest_list.append((chest_index, objs[chest_index]))
return chest_list
#Prints saves a correct sentence for what has been saved
def gained_coin(name, gold, silver, bronze):
#If all of the values are equal to 0
if gold == silver == bronze == 0:
return "{} gained nothing.".format(name)
#If there is only gold
elif gold > 0 and silver == bronze == 0:
return "{} gained {} gold!".format(name, gold)
#If there is only silver
elif silver > 0 and gold == bronze == 0:
return "{} gained {} silver!".format(name, silver)
#If there is only bronze
elif bronze > 0 and gold == silver == 0:
return "{} gained {} bronze!".format(name, bronze)
#If there is only gold and silver
elif gold > 0 and silver > 0 and bronze == 0:
return "{} gained {} gold and {} silver!".format(name, gold, silver)
#if there is only gold and bronze
elif gold > 0 and bronze > 0 and silver == 0:
return "{} gained {} gold and {} bronze!".format(name, gold, bronze)
#If there is only bronze and silver
elif bronze > 0 and silver > 0 and gold == 0:
return "{} gained {} silver and {} bronze!".format(name, silver, bronze)
#If there is gold, silver and bronze
elif gold > 0 and silver > 0 and bronze > 0:
return "{} gained {} gold, {} silver, and {} bronze!".format(name, gold, silver, bronze)
#This is the gui for the bag selection in the inventory
# It shows all of the weapons / armor that the user
# has in their bag, as well as which one is selected
def inventory_bag_gui(obj, selection):
bag = obj.inventory['bag'] #Get the bag
len_index = lambda i, d: len(d[i]) #Returns length of value in that index of d
bag_print = {}
#Go through and make a string corresponding
# to what will be printed out of those items
for index in bag: bag_print[index]="| {}: {} ({})".format(index, bag[index], (lambda i,v: '*' if i==v else '')(index, selection))
hang_int = 0 #Used for the number of underscores we need
#Add up the lengths for all items
for index in bag: hang_int += len_index(index, bag_print)
hang_int = (hang_int // 6) + 10 #Finish off the average, and add 10
#The string of underscores that is 'hang_int' long
hangover = "_" * int(hang_int)
print(" "+hangover)
print("| INVENTORY | BAG: ")
print("|"+hangover)
print("| ESC - Exit bag")
print("| W / S - Move through items")
print("| D - Destroy item")
print("| Enter - Pick item\n|")
#Show the user the armor that they have on currently
print("| Equipped armor:")
print("| {} (mod: {})".format(obj.inventory['armor'][1], obj.inventory['armor'][0]))
#Show the user the weapon they are using currently
print("| Equipped weapon:")
print("| {} (mod: {})\n|".format(obj.inventory['primary'][1], obj.inventory['primary'][0]))
#Go through and print every item, show which one is picked
for index in bag: print(bag_print[index])
print("|"+hangover)
#Lets user manage things in their bag, i.e
# put armor / weapons into the bag, or equip stuff
# that is in the bag.
def inventory_bag(obj):
#a list of all armor
armors_list = [
'Chain mail', 'Leather armor',
'Plate mail', 'Mystic armor',
'Cursed armor', 'Useless armor',
'Paper armor', 'Super cursed armor',
'Armor of nonexistence', 'Bare-flesh armor',
'Scale mail', "Richard's Mask"
]
#A list of all of the weapons
weapons_list = [
'Knife', 'Short sword',
'Blade of honor', 'Blade of the warrior',
'Excaliber', 'Cursed knife',
'Useless knife', 'Healer of the enemy',
'Toothpick',
'Super toothpick',
'Kitchen knife', 'Sacrificial dagger',
'Scimitar', 'Sledgehammer',
'Excalilame', "Richard's Bat"
]
key_press = "" #Keypress option of the player
selected_item = 1 #The item selected to equip
while key_press != "\x1b": #While the key isn't escape
clear() #Clear screen
#Print the gui, show what item is selected
inventory_bag_gui(obj, selected_item)
try:
key_press = Getch()
except:
key_press = "" #So we don't blow up
#Exit out of the bag part of the inventory
if key_press == "\x1b":
break
#If their key-press is to move up / down through bag items
elif key_press.lower() == "w" or key_press.lower() == "s":
#If the user wants to move up one item for selection
if key_press.lower() == "w" and selected_item > 1:
selected_item -= 1 #Sub 1 from selection variable
#If the user wants to move down one item for selection
elif key_press.lower() == "s" and selected_item < 6:
selected_item += 1 #Add 1 to selected variable
#If the user made their selection..
elif key_press == "\r":
#If the item that they have selected is 'None'..
# ask if the user wants to equip it as armor or as a weapon
if obj.inventory['bag'][selected_item][1] == "None":
print(" ____________________________________________")
print("| Do you want to remove your Armor or Weapon?")
print("|\n| A - Remove armor \n| W - Remove weapon\n| C - Cancel")
print("|____________________________________________")
#This is so we can check if they either want to remove
# their armor, remove their weapon, or to cancel
answers_we_will_accept = ['a', 'w', 'c']
query_answer = "" #The answer of the user
#Keep getting input for their answer until we have an
# acceptable answer that we can actually use
while not query_answer.lower() in answers_we_will_accept:
try:
query_answer = Getch()
except:
query_answer = "" #Set it to nothing so we don't explode
#If they want to cancel, and didn't want this, stop this
if query_answer.lower() == "c":
pass
#If they want to remove their armor, let them.
elif query_answer.lower() == "a":
#Put their armor into their bag, in the given position
obj.inventory['bag'][selected_item] = obj.inventory['armor']
#Remove the user's armor
obj.inventory['armor'] = (0, 'None')
#If the user wants to remove their weapon, let them
elif query_answer.lower() == "w":
#Stores the user's weapon into the spot in their bag
obj.inventory['bag'][selected_item] = obj.inventory['primary']
#Remove the user's weapon
obj.inventory['primary'] = (0, 'None')
#If the thing that they are selecting is a weapon, then
# switch out the user's weapon, with the weapon in that bag slot
elif obj.inventory['bag'][selected_item][1] in weapons_list:
#The weapon of the user
users_weapon = obj.inventory['primary']
#Give the user the weapon in their bag
obj.inventory['primary'] = obj.inventory['bag'][selected_item]
#Put the user's previous weapon in the bag slot
obj.inventory['bag'][selected_item] = users_weapon
#If the thing that they (the user) is selecting armor,
# switch the armor that is equipped for the selected armor
elif obj.inventory['bag'][selected_item][1] in armors_list:
#The armor of the user
users_armor = obj.inventory['armor']
#Give the user the armor they selected
obj.inventory['armor'] = obj.inventory['bag'][selected_item]
#Put the user's armor into the bag slot that they pulled from
obj.inventory['bag'][selected_item] = users_armor
#If the user wants to destroy the selected item
elif key_press.lower() == "d":
answers = ['y', 'n'] #Answers we accept
users_answer = ""
print(" ____________________________________________")
print("| Are you sure you want to destroy this item?\n|")
print("| Y - yes | N - No")
print("|____________________________________________")
#While the user doesn't give us an answer we allow
while not users_answer.lower() in answers:
try:
users_answer = Getch()
except:
users_answer = "" #So we don't explode
#If the user doesn't want to destroy the item
if users_answer.lower() == "n":
pass
#If the user does want to destroy the item
elif users_answer.lower() == "y":
#remove the item
obj.inventory['bag'][selected_item] = (0, 'None')
return obj #Return object
#The inventory gui-thingy
def inventory(obj):
option = "" #Character option
#keep going until 'escape'
while option != "\x1b":
#Gets the number of gold
GOLD = obj.inventory['gold']
#Gets silver
SILVER = obj.inventory['silver']
#Gets bronze
BRONZE = obj.inventory['bronze']
#Armor class
Armor_Class = obj.armor_class
#Armor class with Armor
AC_with_armor = obj.armor_class + obj.inventory['armor'][0]
#Weapon name
weapon_name = obj.inventory['primary'][1]
#Weapon damadge
weapon_dmg = obj.inventory['primary'][0]
#Health potions
health_potions = obj.inventory['health potions']
clear() #Clear screen
print(" _____________________________________")
print("| INVENTORY:")
print("|_____________________________________")
print("| ESC - Exit Inventory\n| E - Look through bag\n| F - Use health potion\n|")
#Give player name
print("| Player: {}".format(obj.name))
#Print player health
print("| Health: {}".format(obj.hp))
#Prints out the gold, silver and bronze
print("| Gold: {}\n| Silver: {}\n| Bronze: {}".format(GOLD, SILVER, BRONZE))
#Prints the weapon name, and damadge it deals
print("| Weapon: {} (modifier: {})".format(weapon_name, weapon_dmg))
#Shows to the user the armor that they have on
print("| Armor: {} (modifier: {})".format(obj.inventory['armor'][1], obj.inventory['armor'][0]))
#Prints out the armor class (and armor class w/ armor)
print("| Armor class: {} (with armor {})".format(Armor_Class, AC_with_armor))
#Shows how many potions that the player has
print("| Health potions: {}".format(health_potions))
print("|_____________________________________")
#In case the input was unable to be used (arrow keys)
try:
option = Getch()
except:
option = "\x1b"
#If a potion is being used
if option.lower() == "f" and health_potions > 0:
#If the hp + 5 is exactly 100
if obj.hp + 5 < 100:
#Add 5 hp to the player
obj.hp += 5
#Subtraacts 1 from the number of potions
obj.inventory['health potions'] -= 1
#If exactly 100
elif obj.hp + 5 == 100:
obj.hp += 1
obj.inventory['health potions'] -= 1
#Make the hp equal exactly 100
elif obj.hp + 5 > 100 and obj.hp < 100:
obj.hp = 100
#Subtraacts 1 from the number of potions
obj.inventory['health potions'] -= 1
#If the user wants to go through their bag
elif option.lower() == "e":
#Enter the bag interface
obj = inventory_bag(obj)
#make sure changes to object are saved
return obj
#Generates a number of potions for chests
def gen_potions():
#The number of potions
n = randint(-3, 5)
#If n is <= 0, we'll have 0 potions
if n <= 0:
return 0
#Return n, as the number of potions
else:
return n
#Selects a piece of armor that will be returned
def pick_armor():
#THe armor that we will return
armor = {
0:(2, 'Chain mail'), 1:(4, 'Leather armor'),
2:(7, 'Plate mail'), 3:(9, 'Mystic armor'),
4:(rand(-5, -1), 'Cursed armor'), 5:(0.5, 'Useless armor'),
6:(1, 'Paper armor'), 7:(rand(-10*10**5, -1), 'Super cursed armor'),
8:(0, 'Armor of nonexistence'), 9:(-10, 'Bare-flesh armor'),
10:(0, 'None'), 11:(8, 'Scale mail'), 12:(0, 'None'), 13:(0, 'None'),
14:(0, 'None'), 15:(0, 'None')
}.get(randint(0, 15))
return armor
#Selects a weapon randomly and returns it
def pick_weapon():
#Pick out a weapon to return
weapon = {
0:(2, 'Knife'), 1:(5, 'Short sword'),
2:(8, 'Blade of honor'), 3:(10, 'Blade of the warrior'),
4:(16, 'Excaliber'), 5:(rand(-5,-1), 'Cursed knife'),
6:(0.5, 'Useless knife'), 7:(rand(-10*10**5,-1), 'Healer of the enemy'),
8:(0.01, 'Toothpick'), 9:(0, 'None'), 10:(0, 'None'), 11:(0, 'None'),
12:(0, 'None'), 13:(0, 'None'), 14:(0.1, 'Super toothpick'),
15:(3, 'Kitchen knife'), 16:(7, 'Sacrificial dagger'),
17:(7, 'Scimitar'), 18:(12, 'Sledgehammer'),
19:(rand(0, 13), 'Excalilame')
}.get(rand(0,19))
return weapon
#This is the class of every chest instance
class Chest:
def __init__(self):
#Position of chest
self.pos = (0,0)
#Character that represents this object
self.char = "#"
#Index of this chest
self.index = 0
#The random number of health potions contained
self.health_potions = gen_potions()
#Generates a random amount of coins
# that will be stored in the chest
self.coins = {
'gold':rand(0, 10), #Number of gold
'silver':rand(0, 15), #Number of silver
'bronze':rand(0, 20) #Number of bronze
}
#Randomly generates an amount of potions
self.hp_potions = rand(0, 5)
#The armor contained in the chest
self.armor = pick_armor()
#Primary weapons
self.weapon = pick_weapon()
#If there is mystic armor, and the weapon is Excaliber,
# then re-pick the weapon, so that there isn't Excaliber
if self.armor[1]=="Mystic armor" and self.weapon[1]=="Excaliber":
self.weapon = {
0:(2, 'Knife'), 1:(5, 'Short sword'),
2:(8, 'Blade of honor'), 3:(10, 'Blade of the warrior'),
4:(rand(-5,-1), 'Cursed knife'),
5:(0.5, 'Useless knife'), 6:(rand(-10*10**5,-1), 'Healer of the enemy'),
7:(0.01, 'Toothpick'), 8:(0, 'None'), 9:(0, 'None'), 10:(0, 'None'),
11:(0, 'None'), 12:(0, 'None'), 13:(0.1, 'Super toothpick'),
14:(3, 'Kitchen knife'), 15:(7, 'Sacrificial dagger'),
16:(7, 'Scimitar'), 17:(12, 'Sledgehammer'),
18:(rand(0, 13), 'Excalilame')
}.get(rand(0,18))
#If the roll to get "Richard's Mask" is 1, then
# see if this chest spawns "Richard's Mask"
if self.armor[1]=="Mystic armor" and randint(1, 100)==1:
#Okay, so if 42 is 'rolled' out of 0 -> 1 (50-50 chance)
# then that means that the user get's "Richard's Mask"
self.armor = {1:(10, "Richard's Mask")}.get(rand(0,1), self.armor)
#If the roll to get "Richard's Bat" is 1,
# then see if this chest spawns "Richard's Bat"
elif self.weapon[1]=="Excaliber" and randint(1,100)==1:
#If 42 is rolled randomly from 0 -> 1 (50-50 chance)
# then the player gets "Richard's Bat", otherwise, just Excaliber
self.weapon = {1:(10, "Richard's Bat")}.get(rand(0,1),self.weapon)
#This will 'open' the chest, allowing
# the player to take any coins, potions,
# or to put on some armor
def open_chest(self, obj):
#The option for this chest
option = ""
msg_list = [] #List of messages to user
#Keeping going until escape is pressed
while option != "\x1b":
#Prepare statement for the armor owned
owned_armor = "| Contained Armor: {} (modifier: {})".format(self.armor[1], self.armor[0])
clear()
#These are the label thing
print(" "+('_'*len(owned_armor)))
print("| CHEST {}".format(self.index + 1))
print("|"+('_'*len(owned_armor)))
#Give the options to the players
print("| ESC - Stop looting chest\n| F - Take potions")
print("| E - Take coins\n| R - Equip armor\n| C - Equip weapon")
print("| B - Put weapon / armor in bag\n| ")
#Prints the name of weapon and damage
print("| Weapon: {} (modifier: {})".format(self.weapon[1], self.weapon[0]))
#Shows to the player the armor
print(owned_armor)
#Shows the amount of health potions contained
print("| Health potions: {}".format(self.hp_potions))
#Shows all of the GOLD, SILVER and BRONZE
print("| Coins:")
print("| Gold: {}".format(self.coins['gold']))
print("| Silver: {}".format(self.coins['silver']))
print("| Bronze: {}".format(self.coins['bronze']))
print("|"+('_'*len(owned_armor)))
#Print out message
for msg in msg_list: print(msg)
#Make sure that the user doesn't fuck up
try:
option = Getch()
except:
option = ""
#Gets all of the coins
GOLD = self.coins['gold']
SILVER = self.coins['silver']
BRONZE = self.coins['bronze']
#Give the player all of the coins
if option.lower() == "e":
#Give the player all of the gold coins
obj.inventory['gold'] += self.coins['gold']
#Give the player all of the silver coins
obj.inventory['silver'] += self.coins['silver']
#Give the player all of the bronze coins
obj.inventory['bronze'] += self.coins['bronze']
#Make all of the coins equal 0
self.coins['gold']=0
self.coins['silver']=0
self.coins['bronze']=0
#Give the player all of the potions
elif option.lower() == "f":
#Give the player all of the health potions
obj.inventory['health potions'] += self.hp_potions
#Set the number of potions to 0
self.hp_potions = 0
#Equip armor onto player
elif option.lower() == "r":
#Switches the chest's armor and the player's armor
self.armor, obj.inventory['armor'] = obj.inventory['armor'], self.armor
#Give player the weapon
elif option.lower() == "c":
self.weapon, obj.inventory['primary'] = obj.inventory['primary'], self.weapon
#If the option is to put the contained armor / weapon into bag
elif option.lower() == "b":
#Asks user if they want to try to put the armor or weapon
# into their inventory
print(" ________________________________________________________")
print("| Would you like to put the armor or weapon in your bag?\n|")
print("| A - Armor | W - Weapon")
print("|________________________________________________________")
#Answers acceptable in this instance
acceptable_answers = ['a', 'w']
user_input = "" #Response from user
#While the response isn't something we 'like'
while not user_input.lower() in acceptable_answers:
try:
user_input = Getch()
except:
#So we don't explode
user_input = ""
#Get the bag slots that are empty
empty_bag_slots = [index for index in obj.inventory['bag'] if obj.inventory['bag'][index][1] == "None"]
#Attempts to put the armor into an empty inventory slot
if user_input.lower() == "a":
#If there are empty bag slots
if len(empty_bag_slots) > 0:
#Puts the armor in the smallest unused bag slot
obj.inventory['bag'][sorted(empty_bag_slots)[0]] = self.armor
self.armor = (0, 'None') #Remove armor from chest
#If there are no empty slots
elif len(empty_bag_slots) == 0:
msg_list.append("Sorry, your inventory is full.")
#Attempts to put hte weapon into an empty inventory slot
elif user_input.lower() == "w":
#If there are empty bag slots to use
if len(empty_bag_slots) > 0:
#Puts weapon into the smallest unused bag slot
obj.inventory['bag'][sorted(empty_bag_slots)[0]] = self.weapon
self.weapon = (0, 'None') #Remove weapon from chest
#If there are no empty slots in the bag
elif len(empty_bag_slots) == 0:
msg_list.append("Apologies, your inventory is full.")
#Return the object
return obj
#Generates a name out of random symbols and letters
def gen_gibberish_name():
#The length of the name
length = randint(3, 7)
#All acceptable names
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789?><~?!@#$%^&"
name = "" #Returned name
while length > 0:
#Add a random character
name += chars[rand(0, len(chars)-1)]
length -= 1 #Decrease number of characters
return name
#Takes all of the coins in the player's possestion,
# and converts as much as possible into gold
# 100 bronze = 1 silver
# 100 silver = 1 gold
def convert_coin_to_gold(obj):
#Number of gold coins
GOLD = obj.inventory['gold']
#Number of silver coins
SILVER = obj.inventory['silver']
#Number of bronze coins
BRONZE = obj.inventory['bronze']
#If the silver and bronze is 0
# (stop so we don't get an error)
if SILVER == BRONZE == 0:
return obj #Prematurely stop
# Adds new silver to total silver | The remaining bronze
SILVER, BRONZE = SILVER + int(BRONZE / 100), BRONZE % 100
# Adds new gold to total gold | The remaining silver
GOLD, SILVER = GOLD + int(SILVER / 100), SILVER % 100
#Now give the user the total number of gold
obj.inventory['gold'] = GOLD
#Now give the user the remaining silver
obj.inventory['silver'] = SILVER
#Now give the user the reamining bronze
obj.inventory['bronze'] = BRONZE
return obj #Now return the object
#This will tell the user if there is any sort of change
# the the amount of currency that they have
def show_convert(obj):
#Gets the gold and silver before the transaction
before_silver, before_gold = obj.inventory['silver'], obj.inventory['gold']
#Converts currency
obj = convert_coin_to_gold(obj)
#Gets the amount of silver and gold after transaction
after_silver, after_gold = obj.inventory['silver'], obj.inventory['gold']
#IF the amount of gold and silver isn't the same, then tell the user
# how much silver was converted into gold
if before_silver != after_silver and before_gold != after_gold:
print("{} silver was converted into {} gold pieces!".format((after_gold - before_gold)*100, after_gold - before_gold))
pause()
return obj
#This method is for buying things from the shop-keep
def buy_func(name, sold_armor, sold_weapon, hp_price, weapon, weapon_price, armor, armor_price, obj):
#Gonna have the gui be simular to the shop entry
buy_list = [
#Show the price of health potions
'| Health potions: {} gold (per potion)'.format(hp_price),
#Show the name and modifier of the armor
'| Armor: Name: {}, Mod: {} ({} gold)'.format(armor[1], armor[0], armor_price),
#Show the name and modifier of the armor
'| Weapon: Name: {}, Mod: {} ({} gold)'.format(weapon[1], weapon[0], weapon_price)
]
select = 0 #Selected item to buy
choice = "" #The character option
log = [] #Log feedback
while True:
clear() #Clear the screen
#The thing for hte top and bottom border
len_bottom = '_'*(len(buy_list[1])+int(len(buy_list[2])//2))
#GUI THINGY for the shop
print(' '+len_bottom)
print('| SHOP | BUY SECTION')
print('|'+len_bottom)
print('| ESC - Exit shop (buying section)')
print('| W / S - Go through options')
print('| Enter - Make purchase\n|')
#Shows the user their gold
print("| Your Gold: {}".format(obj.inventory['gold']))
x = 0 #Index
for item in buy_list:
show_select = lambda index, sel: '*' if index==sel else ''
#Prints out items and shows which one is selected
print(item + " ({})".format(show_select(x, select)))
x += 1 #Move onto next
print("|"+len_bottom)
#Prints out all of the messages to the user
for msg in log: print(msg)
log = [] #Clear out the log list
try:
choice = Getch()
except UnicodeDecodeError:
#In the case that the value can't be used
choice = ""
#If the user is done with the shop (BUY SELECTION)
if choice == "\x1b": break
#If the choice is to go up / down through options
elif choice == "w" or choice == "s":
#If we are to move up in options, subtract 1 from select
if choice == "w" and select > 0:
select -= 1
#If we are to move down in options, add 1 from select
elif choice == "s" and select < 2:
select += 1
#If the user made a select choice
elif choice == "\r":
#If the user is buying potions
if select == 0:
#If the user has enough gold to buy a potion, give user one
if obj.inventory['gold'] >= hp_price:
#Give the user an additional potion
obj.inventory['health potions'] += 1
#Subtracts the payment amount from the gold the user has
obj.inventory['gold'] -= hp_price
#Give the user feedback, a 'thank you' for using money
log.append("{}: Thank you for your business!".format(name))
#If the user doesn't have enough money
else:
#Tell the user that they don't have enough money
log.append("{}: I'm sorry, you don't have enough money.".format(name))
#If the user is trying to buy the armor, and it hasn't been bought
elif select == 1:
#If the armor has been sold, tell the user
if sold_armor == True:
log.append("{}: I'm sorry, you already bought this item.".format(name))
#If the user can buy the armor, store it in their bag
elif obj.inventory['gold'] >= armor_price and sold_armor==False:
#Spaces that are not occupied
unusable_spaces = [index for index in obj.inventory['bag'] if obj.inventory['bag'][index][1] == "None"]
#If there are spaces that can be used
if len(unusable_spaces) > 0:
#Sort from smallest to largest index that is unused
unusable_spaces = sorted(unusable_spaces)
#Store the armor away into the user's inventory
obj.inventory['bag'][unusable_spaces[0]] = armor
sold_armor = True #The armor has now been used
armor = (0, 'None') #Set the armor to nothing
#Subtract the price of the armor from the user's things
obj.inventory['gold'] -= armor_price
else:
#Ask the user if they want to put on their armor, and remove their current armor
print("{}: You do not have space in your bag for this item.".format(name))
print("{}: If you like, I can take your armor, and you can put on your new armor.".format(name))
print("{}: But.. you can't take back your old armor, just so you know.")
print("{}: Does that sound good though?\n")
print(" __________________ ")
print("| Y - yes | N - No")
print("|__________________")