-
Notifications
You must be signed in to change notification settings - Fork 7
/
Fallout_Shelter.py
1893 lines (1651 loc) · 64.5 KB
/
Fallout_Shelter.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
"""Text-based Fallout Shelter game developed by T.G."""
"""
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from collections import OrderedDict
from random import randint, randrange
#from appdirs import user_data_dir
import pickle
import sys
import os
from Human import Human, Player, NPC
from Room import Room, all_rooms
from Item import Item, Inventory, all_items
from general_funcs import *
try:
try:
import readline
except ImportError:
import pyreadline as readline
#if can't get any readline library, default to standard IO
except ImportError:
pass
"""
def save_file():
#Generate save file location/name based on system.
#Returns:
#str -- path to save file
sfn = "fstb.p"
if "-l" in sys.argv:
sfp = os.path.split(os.path.abspath(sys.argv[0]))[0]
else:
appname = "Fallout-Shelter-Text-Based"
sfp = user_data_dir(appname=appname, appauthor=False, roaming=True)
return os.path.join(sfp, sfn)
def load_game(_=None, save=_save_file):
Load game from file, `load filename` to load from specific file.
Arguments:
save -- file to load from
Returns:
game -- Game object
with open(save, "rb") as s:
try:
game = pickle.load(s)
except pickle.UnpicklingError:
print_line("Unable to load game.")
return None
print_line("Game loaded from {}.".format(save))
return game
_save_file = save_file()
"""
class Game(object):
"""Main game class."""
def __init__(self):
"""Initilize main game system."""
self.setup_player()
self.all_items = all_items() # Fetches all items from items.json
self.all_rooms = all_rooms() # Fetches all items from rooms.json
#player.inventory = Inventory(self.all_items)
self.player.inventory['turret'] += 1
self.player.inventory["steel"] += 5
self.player.inventory["chip"] += 1
#self.trader_inventory = Inventory(self.all_items)
self.rooms = {
'living' : Room('living'),
'generator' : Room('generator'),
'water' : Room('water'),
#'trader' : Room('trader'),
'kitchen' : Room('kitchen')
}
self.people = {}
self.caps = 100
self.trader_caps = 500
self.happiness = 100
self.action_points = 50
self.defense = 0
self.security = "secure"
self.days = 1
self.overuse = False # If player uses too many action points in one day.
self.actions = OrderedDict() # [('action': function)]
self.first_few()
action_see_people(self)
if check_built_room(self, "trader"):
self = find_rand_items(self, 'trader', 10)
self.actions["quit"] = action_quit
self.actions["skip"] = None
#self.actions["save"] = action_save
#self.actions["load"] = load_game
self.actions["help"] = action_help
self.actions["see day"] = action_see_day
self.actions["see people"] = action_see_people
self.actions["see inventory"] = action_see_inventory
self.actions["see items"] = action_see_inventory
self.actions["see trader"] = action_see_inventory
self.actions["see rooms"] = action_see_rooms
self.actions["see resources"] = action_see_resources
self.actions["auto assign all"] = action_auto_assign
self.actions["trade"] = action_trade
self.actions["craft"] = action_craft
self.actions["rush"] = action_rush_room
self.actions["assign"] = action_assign_to_room
self.actions["unassign"] = action_unassign
self.actions["auto feed all"] = action_auto_feed_all
self.actions["coitus"] = action_coitus
self.actions["build"] = action_build_room
self.actions["fix"] = action_fix_room
self.actions["heal"] = action_heal
def add_action(self, name, action):
"""Add entries to the actions dictionary.
Arguments:
name -- name of action
action -- function to execute
"""
self.actions[name] = action
def setup_player(self):
"""Create player object."""
invalid_name = "Invalid name. Only one word is acceptable."
while True:
name = input("Choose a first name for yourself: ")
if validate_name(name):
first_name = name
break
print_line(invalid_name)
while True:
name = input("What is the surname of your father? ")
if validate_name(name):
father = Human(surname=name)
break
print_line(invalid_name)
while True:
name = input("What is the surname of your mother? ")
if validate_name(name):
mother = Human(surname=name)
break
print_line(invalid_name)
while True:
gender = input("Please enter your gender (M/F): ")
if len(gender) >= 1 and gender[0].upper() in ("M", "F"):
gender = gender[0].upper()
break
print_line("Invalid gender choice.")
self.player = Player(first_name, 0, father, mother, 21, gender)
def first_few(self):
"""Create first few inhabitants with random names."""
used_names = []
names = [
"Thompson",
"Elenor",
"Codsworth",
"Sharmak",
"Luthor",
"Marshall",
"Cole",
"Diven",
"Davenport",
"John",
"Max",
"Lex",
"Leth",
"Exavor"]
for person_name in self.people.keys():
used_names.append(person_name.split(" ")[0])
used_names.append(person_name.split(" ")[1])
load_time(100, "Populating vault with random inhabitants.")
while len(self.people) < 5:
num_1 = randint(0, len(names) - 1)
num_2 = randint(0, len(names) - 1)
if num_1 == num_2:
continue
if names[num_1] in used_names or names[num_2] in used_names:
continue
self.people["{} {}".format(names[num_1], names[num_2])] = NPC(
names[num_1],
self.days,
None,
"Alena",
21,
get_gender(),
names[num_2])
used_names.append(names[num_1])
used_names.append(names[num_2])
def storage_capacity(self):
"""Calculate max inventory capacity of player.
Returns:
capacity -- max inventory capacity of player
"""
capacity = self.rooms["storage"].production
return capacity
def use_points(self, number):
"""Remove action points from total.
Arguments:
number -- how many points to remove
"""
if self.action_points - number < 0: # If overuse occurs, i.e. if overuse is negative
self.overuse = True
self.overuse_amount = 0 - (self.action_points - number)
self.action_points -= number
def run(self, debug=False):
"""Main game. Once all values are initilized or loaded from a save file, this is run."""
action_help(self) # Initially prints the available commands.
while True and self.player.alive: # Day loop
self.action_points = 50
if self.overuse:
self.action_points -= self.overuse_amount
load_time(100, " A new day dawns. It is now day {} in the vault".format(
self.days))
print_line("\n")
self = update_all_room_production(self)
#Room loop
for room in self.rooms.values():
if self.player.inventory['watt'] >= room.wattage:
self.player.inventory['watt'] -= room.wattage #Use power
if room.produce:
self.player.inventory[room.produce] += room.production
else:
print_line("Not enough power to operate room: {}".format(
room.name))
if room.rushed:
room.rushed = False
self = action_auto_feed_all(game)
for person in self.people.values(): #People loop
if person.check_xp():
person.level_up()
person.increase_hunger(10)
if person.hunger > 99:
if self.assigned_room:
self = unassign(self, str(person))
person.die(self, "hunger")
elif person.hunger > 80:
print_line(
"Warning! {} is starving and may die soon".format(
person))
elif person.hunger > 50:
print_line("{} is hungry".format(person))
person.increase_thirst(20)
if person.thirst > 99:
if person.assigned_room:
self = unassign(self, str(person))
person.die(self, "thirst")
elif person.thirst > 80:
print_line("Warning! {} is extremely thristy " +
"and may die soon.".format(str(person)))
elif person.thirst > 50:
print_line("{} is thirsty".format(person))
if person.current_activity != "":
if person.current_activity == "scavenging":
person.take_damage(person, randint(0, 30))
if person.health < 20:
pass # Need to end scavenging.
elif person.current_activity == "guarding":
pass
if person.days_active == person.activity_limit:
if person.current_activity == "scavenging":
print_line("{} has come back from".format(person) +
" scavenging and has found these items:")
# Need to print items found.
person.current_activity = ""
person.active_days = 0
person.activity_limit = 0
else:
person.days_active += 1
if check_built_room(self, 'trader'): #Trader randomly loses and gains items daily
if game.rooms['trader'].assigned:
self = lose_items(self, 'trader', 10)
self = find_rand_items(self, 'trader', 10)
while self.action_points > 0: # Choice loop
print_line("Action Points Remaining: {}".format(self.action_points))
a = input("Choose an action: ")
if len(a) > 0:
action, *args = a.split()
if action.lower() == "skip":
break
elif action in ("trade", "assign", "unassign", \
"auto feed all", "auto assign all", "build", "craft",\
"fix", 'rush', 'coitus', 'heal'):
try:
self = self.actions[action](self, *args)
except TypeError:
print_line("Incorrect number of arguments")
elif a in self.actions.keys():
try:
self.actions[a](self, *args)
except Exception as e:
print_line("Error: {}".format(e))
elif action in ("save", "load"):
self.actions[action](self, args[0])
else:
print_line("Invalid action selected. Try again.")
else:
print_line("You have to choose a valid action.")
self.days += 1
def action_quit(*_):
"""Quit current game.
Arguments:
game -- main game object
"""
save = default_input("Quit without saving? (y/N) ")
if save == "n":
return
else:
sys.exit(0)
"""
def action_save(game, save=_save_file):
Save current game state, `save filename` to save to specific file.
Arguments:
game -- game object to save
save -- file to save to
if os.path.exists(save):
ow = default_input("{} already exists, overwrite? (Y/n) ".format(save))
if ow != 'y':
return
with open(save, "wb") as s:
try:
pickle.dump(game, s)
except pickle.PicklingError:
print_line("Unable to save game.")
return
print_line("Game has been saved to {}.".format(save))
"""
def action_help(game):
"""See help for all actions available.
Arguments:
game -- main game object
"""
print_line('Actions:')
lens = text_align(game.actions)
for i, action in enumerate(game.actions.keys()):
if action == "skip":
desc = "Skip current day."
else:
desc = sentence_split(game.actions[action].__doc__)
print_line('{}{}: {}'.format(
action,
' ' * (2 + lens[i]),
desc),
speed=FAST)
print_line("\n")
def action_see_day(game, *args):
"""See current day number.
Arguments:
game -- main game object
"""
print_line("It is currently day number {} in the vault.".format(game.days))
def action_see_people(game, *args):
"""Display info of all inhabitants.
Arguments:
game -- Main game object
"""
game.player.print_()
for person in game.people.values():
person.print_()
def action_see_inventory(game, inventory):
"""See given inventory's contents.
Arguments:
game -- main game object
inventory -- inventory to print
"""
inv = inventory.lower()
if inv == "inventory":
game.player.inventory.print_()
elif inv == "trader":
game.trader_inventory.print_()
else:
print("No inventory named '{}' exists.".format(inventory))
def action_see_rooms(game, *args):
"""Print each room with details.
Arguments:
game -- main game object
"""
game = update_all_room_production(game)
for room in game.rooms.values():
room.print_()
def action_see_resources(game, *args):
"""See available resources (food, water, and power).
Arguments:
game -- Main game object
"""
print_line("Food * ", game.player.inventory["food"])
print_line("Water * ", game.player.inventory["water"])
print_line("Power * ", game.player.inventory["watt"])
def living_capacity(game):
"""Get maximum inhabitant capacity of shelter.
Arguments:
game -- main game object
Returns:
int -- maximum capacity of shelter
"""
room = game.rooms["living"]
print_line("Maximum number of inhabitants", 5 * room.level)
return (5 * room.level)
# Construction system:
def action_build_room(game, room_name):
#Need to check if player has the materials to build room
"""Build room specified.
Arguments:
game -- Main game object
room_name -- name of room to build
Returns:
game -- Main game object
"""
if check_room(game, room_name):
if not check_built_room(game, room_name):
room = Room(str(room_name)) # creates a room.
game.rooms[str(room_name)] = room # Stores the room in memory.
load_time(50, "Building " + room_name)
for y in room.components: # Does this for each component
game.player.inventory[y] -= 1
#game.player.gain_xp(100) #Commented out for now since levelling up
# system doesn't work
game.use_points(50)
else:
print_line("You've already built the {} room.".format(room_name.title()))
else:
print_line("{} isn't a valid room name.".format(room_name.title()))
return game
def action_craft(game, item_name):
"""Craft specified item.
Arguments:
game -- Main game object
item_name -- name of item to craft
Returns:
game -- Main game object
"""
if can_craft_item(game, item_name):
load_time(5, ("Crafting ", item_name))
game.player.inventory[item_name] += 1
# Perk bonuses
item = Item(item_name)
chance = game.player.stats["crafting"]
for component in item.components:
if randint(1,101) > chance:
#The higher the player's crafting level, the less
#likely they are to lose their items.
game.player.inventory[component] -= 1
#game.player.gain_xp(item.rarity * 10)
#game.use_points(5)
return game
def action_scrap(game, item):
"""Deletes an item from the inventory and adds it's components to the inventory
Arguments:
game -- Main game object
item -- name of item being scrapped
Returns:
game -- Main game object
"""
it = Item(item)
for component in it.components:
game.player.inventory[component] += 1
game.player.inventory[item] -= 1
return game
# Human management system:
def get_gender():
"""Randomly generate gender for NPC.
Returns:
char -- 'm' or 'f'
"""
if randint(0, 1) == 0:
return "m"
else:
return "f"
def check_person(game, name):
"""Check if inhabitant exists in list of all inhabitants.
Arguments:
game -- Main game object
name -- full name of person
Returns:
bool -- whether inhabitant exists or not
"""
#print("Checking to see if {} exists".format(name.title()))
if name.title() in game.people.keys():
return True
else:
print_line("{} {} does not exist").format(name.split()[0], name.split()[1])
return False
def action_assign_to_room(game, *args):
""" Assign a person to a room.
In the form "assign first_name surname to room"
Arguments:
game -- main game object
first_name -- first_name of person
surname -- surname of person
room -- room to assign to
Returns:
game -- Main game object
"""
if (len(args) == 4) and (args[2] == "to"):
if check_person(game, str(args[0]) + " " + str(args[1])):
if check_built_room(game, args[3]):
game = assign_to_room(game,
args[0].title() + " " + args[1].title(),
args[3])
else:
if not check_room(game, args[3]):
print_line("This room doesn't exist")
else:
print_line("You need to build the {} room".format(args[4]))
else:
print_line("Invalid syntax. Must be in form of (assign cole leth to living)")
return game
def assign_to_room(game, person_name, room_name):
"""Assign Human to room, assuming all inputted arguments are valid.
Arguments:
game -- Main game object
person_name -- full name of person being assigned (with first letter's capitalized)
room_name -- name of room to assign to
"""
room = game.rooms[room_name]
person = game.people[person_name]
if room.count_assigned() < room.assigned_limit:
if person.assigned_room: #If person is already assigned to a room, unassigns them.
game = unassign(game, person_name)
room.assigned.append(person_name)
person.assigned_room = room_name
game.use_points(1)
print_line("{} has been assigned to the {}".format(person_name, str(room)))
else:
print("The {} has {} people assigned and can hold no more".format(str(room), room.count_assigned()))
return game
def action_unassign(game, *args):
""" Unassigns person from their room.
Checks to see if all arguments are valid, then passes them to
unassing() function. Only called by the player.
Arguments:
game -- main game object
name -- name of person to unassign
Returns:
game -- Main game object
"""
name = str(args[0] + " " + args[1]).title()
print("Input name is", name)
if len(name.split()) == 2:
if check_person(game, name):
game = unassign(game, name)
print_line("{} has been unassigned from their room.".format(name))
else:
print_line("The name must be of type: 2 words")
return game
def unassign(game, name):
""" Unassigns person from their room.
Arguments:
game -- main game object
name -- name of person to unnassign
Returns:
game -- Main game object
"""
name.title()
person = game.people[name]
room = game.rooms[person.assigned_room]
person.assigned_room = ""
room.assigned.remove(name)
return game
def action_coitus(game, *args):
"""Have two adults try for a child.
Arguments:
game -- main game object
parent_1 -- name of first parent
parent_2 -- name of second parent
Returns:
game -- main game object
"""
if len(args) > 1:
print(args)
print(args[0])
# if args[-1] == args[3]:
parent_1_name = (args[0] + " " + args[1]).title()
print("parent name:", parent_1_name)
if check_person(game, parent_1_name):
parent_1 = game.people[parent_1_name]
parent_2_name = (args[2] + " " + args[3]).title()
if check_person(game, parent_2_name):
parent_2 = game.people[parent_2_name]
person = create_npc(parent_1, parent_2,game.days)
game.people[str(person)] = person
parent_1.children.append(person.name + " " + parent_1.surname)
parent_2.children.append(person.name + " " + parent_1.surname)
parent_1.partner = parent_2.name + " " + parent_2.surname
parent_2.partner = parent_1.name + " " + parent_1.surname
if game.days > 2: # First few births cost no points
use_points(50)
# else:
# print_line("Invalid input. You have to input two names")
return game
def create_npc(
parent_1,
parent_2,
day_count):
"""Create new child inhabitant.
Arguments:
parent_1 -- parent of new child
parent_2 -- parent of new child
Returns:
person -- New NPC
"""
while True:
name = input("Choose a first name for the new child: ")
if len(name.split()) == 1: # Player can only input one word
name = name.title() # Capitalizes first letter
if parent_2.gender == "m":
parent_1, parent_2 = parent_2, parent_1 #Ensure father
#is parent_1, for surname purposes.
person = NPC(
name,
day_count,
parent_1,
parent_2,
0,
get_gender())
load_time(50, (name.title() + " is being born!"))
return person
else:
print_line("You have to input a single word!")
def create_player():
"""Create player inhabitant.
Returns:
Player -- player object
"""
while True:
name = input("Choose a first name for yourself: ")
if len(name) <= 0:
print_line("You need a name!")
elif len(name.split()) != 1:
print_line("Only single word inputs are accepted.")
else:
name = name.title()
break
while True:
parent_1 = input("What is the surname of your father? ")
if len(parent_1) <= 0:
print_line("Your father needs a surname!")
elif len(parent_1.split()) != 1:
print_line("Only single word inputs are accepted.")
else:
parent_1 = parent_1.title()
break
while True:
parent_2 = input("What is the surname of your mother? ")
if len(parent_2) <= 0:
print_line("Your mother needs a surname!")
elif len(parent_2.split()) != 1:
print_line("Only single word inputs are accepted.")
else:
parent_2 = parent_2.title()
break
while True:
gender = input("What is your gender?(m/f) ")
if len(gender) == 0:
print_line("You need a gender.")
elif gender[0].lower() not in ("m", "f"):
print_line("Invalid input. Only accepts 'm' or 'f'.")
else:
gender = gender[0].lower()
break
return Player(
name,
0,
parent_1,
parent_2,
21,
gender)
def action_auto_assign(game, *args):
"""Automatically assign inhabitants to rooms.
Arguments:
game -- Main game object
"""
while True:
for room in game.rooms.values():
if room.count_assigned() < room.assigned_limit:
for person in game.people.values():
if not person.assigned_room:
break
game = assign_to_room(game, str(person), room.name)
unemployed_count = 0
for person in game.people.values():
if not person.assigned_room:
unemployed_count +=1
if unemployed_count == 0:
break
return game
def action_heal(game, *args):
""" Heal an inhabitant.
Player chooses to heal an inhabitant, possibly themselves.
In the form (heal Thomas Paine by 10)
Arguments:
game -- Main game object
first_name -- first_name of person
surname -- surname of person
amount -- base amount they want to heal by
Returns:
game -- Main game object
"""
player = game.player()
if len(args) > 0 and len(args.split()) == 4:
name = args[0] + " " + args[1]
if check_person(game, name):
person = game.people[name]
try:
amount = int(args[-1])
if player.medic > 0: # Medic Boost.
amount = amount * (1 + (0.05 * player.medic))
if person.HP == person.max_HP():
print_line("{} is already at max health.".format(person))
else:
person.heal(amount)
except:
print_line("You can only heal by an integer amount")
else:
print_line("Heal command must be in form: heal Thomas Paine by \
10 ")
return game
# Room Management system:
def action_rush_room(game, room):
"""Rush a room in the game.
Arguments:
game -- Main game object
room -- name of room to rush
Returns:
game -- main game object
"""
try:
room = game.rooms[room]
except KeyError:
print_line("No such room!")
return game
if not room.can_rush:
print_line("Cannot rush {}".format(room))
return game
room.rush()
random = randint(0,101)
if random < room.risk:
print_line(" The {} room has been broken.".format(room.name))
room.broken = True
else:
room.rushed = True
return game
def check_room(game, room):
"""Check if room exists.
Arguments:
game -- main game object
room -- room to check for
Returns:
bool -- whether room exists or not
"""
if room in game.all_rooms:
return True
return False
def check_built_room(game, room):
"""Check if room has been built yet.
Arguments:
game -- main game object
room -- room to check for
Returns:
bool -- whether room has been built or not
"""
if room in game.rooms:
return True
print("{} has not been built yet".format(room))
return False
def can_use_power(game, room):
"""
Determine whether the room may use power or not.
Arguments:
game -- main game object
room - room which uses power
Returns:
bool -- whether room may use power
"""
if game.player.inventory["watt"] > room.power_usage:
return True
else:
return False
def power_usage(game):
"""Check total power needed.
Arguments:
game -- main game object
Returns:
total -- total power needed by all rooms
"""
total = 0
for room in game.rooms:
total += room.power_usage
return total
def power_production(game):
"""Check total power being produced.
Arguments:
game -- main game object
Returns:
production -- total amount of power being produced
"""
generator = game.rooms['generator']
return generator.production
def action_fix_room(game, room_name):
"""Tries to fix room.
Arguments:
game -- Main game object
room_name -- Name of room to try to fix
Returns:
game -- Main game object
"""
if check_room(game, room_name):
if check_built_room(game, room_name):
room = game.rooms[room_name]
if room.broken:
can_fix = True
items_needed = Inventory(game.all_items)
for component in room.components:
if randrange(0,1) == 0:
items_needed[component] += 1
for item_needed in items_needed.keys():
if game.player.inventory[item_needed] \
< items_needed[item_needed]:
can_fix = False
print_line("You don't have enough {} to fix\
{} room".format(item_needed, room_name))
if can_fix:
room.fix()
else:
print_line("{} room doesn't need to be fixed".format(room_name))
else:
print_line("You haven't built the {} room yet".format(room_name))
else:
print_line("Invalid room name: {}".format(room_name))
return game
def update_all_room_production(game):
for room in game.rooms.values():
production = 0
if room.broken:
print_line(room.name, "is broken and needs to be fixed.")
else:
player = game.player
if room.attribute:
attribute = room.attribute