-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1989 lines (1694 loc) · 75.2 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
from __future__ import annotations
import copy
import json
import math
import random
from pprint import pprint
import scipy.stats
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import scipy.spatial.distance
import itertools
import collections
from base import *
from entity import *
from event import *
from typing import List, Dict
# https://stackoverflow.com/questions/287871/print-in-terminal-with-colors
class BColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Parser:
words = {
"article": ["a", "an", "the"],
"preposition": ["of", "in", "to", "for", "with", "on", "at", "from", "by", "about", "as",
"into", "like", "through", "after", "over", "between", "out", "against",
"during", "without", "before", "under", "around", "among"],
"intensifier": ["fucking"]
}
verbs = {
"pickup": ["pickup", "grab", "get", "take", "pick"],
"drop": ["drop", "place", "put"],
"move": ["go", "move", "walk", "run"],
"direction": ["north", "south", "east", "west", "up", "down", "left", "right",
"n", "s", "e", "w", "u", "d", "l", "r"],
"look": ["look", "examine", "search"],
"use": ["use", "touch"],
"talk": ["talk", "speak", "t"],
"inventory": ["inv", "inventory"],
"key": ["key", "k"],
"map": ["map"],
"give": ["give"]
}
player: Player
commandList: List[str]
def __init__(self, player):
self.player = player
self.commandList = []
def split_commands(self, command_str):
self.commandList = command_str.split(" ") + ["", "", "", ""]
if (self.commandList[0] == "pick" and self.commandList[1] == "up") \
or (self.commandList[0] == "drop" and self.commandList[1] == "down") \
or (self.commandList[0] == "put" and self.commandList[1] == "down"):
self.commandList[0:2] = [''.join(self.commandList[0:2])]
def parse_commands(self, command_str):
self.split_commands(command_str)
self.strip_commands()
verb = self.identify_verb().lower()
direct_object = self.identify_object(verb).lower()
self.commandList[0] = verb
self.commandList[1] = direct_object
return self.commandList
def identify_verb(self):
# look at first word, see if it matches any of the known verbs
verb = self.commandList[0]
best_verb = ""
for key, testVerbs in self.verbs.items():
if verb in testVerbs:
best_verb = key
if best_verb == "direction":
best_verb = "move"
self.commandList.insert(0, "")
break
return best_verb
def identify_object(self, verb):
direct_object = self.commandList[1]
# based on verb do different things
if verb == "move":
if direct_object == "n":
direct_object = "north"
if direct_object == "s":
direct_object = "south"
if direct_object == "e":
direct_object = "east"
if direct_object == "w":
direct_object = "west"
if direct_object == "u":
direct_object = "up"
if direct_object == "d":
direct_object = "down"
# if player misspelled actor name
if verb == "talk" and direct_object:
actor = self.player.get_current_room().get_actor_when_visible(direct_object)
topic = " ".join(filter(lambda x: len(x) > 0, self.commandList[2:]))
if actor is None:
direct_object = self.sp_entity_name(direct_object, self.player.get_current_room().get_actors_visible(),
0.7)
actor = self.player.get_current_room().get_actor_when_visible(direct_object)
if actor and not actor.check_topic(topic, self.player.get_keys()):
topic = self.sp_event_name(topic, actor.get_topics_list(self.player.get_keys()), .4)
self.commandList[2] = topic
if verb == "move":
direct_object = self.sp_link_name(direct_object, self.player.get_current_room().get_links(), 0.7)
if verb in ["pickup"]:
direct_object = self.sp_entity_name(direct_object, self.player.get_current_room().get_items_visible(), 0.7)
if verb in ["look"]:
direct_object = self.sp_entity_name(direct_object, self.player.get_current_room().get_items_visible() +
self.player.get_current_room().get_actors_visible(), 0.7)
if verb in ["use"]:
direct_object = self.sp_entity_name(
direct_object,
self.player.get_current_room().get_items_visible() + self.player.get_inventory(),
0.7)
if verb in ["drop"]:
direct_object = self.sp_entity_name(direct_object, self.player.get_inventory(), 0.7)
if verb in ["give"]:
actor = self.player.get_current_room().get_actor_when_visible(direct_object)
give_object = self.sp_entity_name(self.commandList[2], self.player.get_inventory(), 0.7)
self.commandList[1] = actor
self.commandList[2] = give_object
return direct_object
def collect_entity_list(self):
# get entities in location
location = self.player.get_current_room()
entity_list = location.get_items_visible()
entity_list += location.get_actors_visible()
# get items in player inventory
entity_list += self.player.get_inventory()
return entity_list
def collect_entities_from_entity(self, entity):
return_list = [entity]
inventory_list = entity.get_inventory()
for inventoryItem in inventory_list:
return_list += self.collect_entities_from_entity(inventoryItem)
return return_list
@staticmethod
def sp_entity_name(word, entity_list: List[Entity], threshold):
# find closest actor name
if not word:
return ""
correct_list = {}
for entity in entity_list:
if not entity.get_visible():
continue
entity_name = entity.get_name()
character_length = min(len(entity_name), len(word))
counter = 0
for i in range(character_length):
counter += 1 if entity_name.lower()[i] == word.lower()[i] else 0
correct_list[entity_name] = counter / character_length
if not correct_list:
return word
key = max(correct_list, key=lambda x: correct_list[x])
if correct_list[key] > threshold:
word = key
return word
@staticmethod
def sp_link_name(word, link_list: List[Link], threshold):
# find closest actor name
if not word:
return ""
correct_list = {}
for link in link_list:
link_name = link.get_direction()
character_length = min(len(link_name), len(word))
counter = 0
for i in range(character_length):
counter += 1 if link_name.lower()[i] == word.lower()[i] else 0
correct_list[link_name] = counter / character_length
if not correct_list:
return word
key = max(correct_list, key=lambda x: correct_list[x])
if correct_list[key] > threshold:
word = key
return word
# these are for dialogues but events might be extended to include something else so keeping the name event for now
@staticmethod
def sp_event_name(word, event_list, threshold):
# find closest actor name
if not word:
return ""
correct_list = {}
for event_name in event_list:
character_length = min(len(event_name), len(word))
counter = 0
for i in range(character_length):
counter += 1 if event_name.lower()[i] == word.lower()[i] else 0
correct_list[event_name] = counter / character_length
if not correct_list:
return word
key = max(correct_list, key=lambda x: correct_list[x])
if correct_list[key] > threshold:
word = key
return word
# strip commandList of unnecessary words?
def strip_commands(self):
counter = 0
while counter < len(self.commandList):
word = self.commandList[counter]
if word in self.words["article"]:
self.commandList.remove(word)
continue
elif word in self.words["preposition"]:
self.commandList.remove(word)
continue
elif word in self.words["intensifier"]:
self.commandList.remove(word)
continue
counter += 1
class ScenarioBuilder:
scenarioList: List[Scenario]
player_model: Dict[str, float]
currentScene: Scenario
player: Player
state: str
action_choices = ["pickup", "look", "talk", "use"]
def __init__(self, history_length=10, model=None):
self.scenarioList = []
self.current_model = {}
self.action_history = []
self.action_prob_dict = {}
self.history_length = history_length
self.build_scenarios(["boring.json", "cat.json"])
self.state = "wait"
self.distraction_timeout = 0
self.max_distraction_timeout = 0
self.distracted = False
self.player = None
self.large_threshold = .2
self.small_threshold = 0
if model is None:
self.player_model = {}
self.reset_model()
else:
self.player_model = model
self.normalize_player_model()
self.initialize_actions()
for action in self.action_choices:
self.current_model[action] = 0
pass
def build_scenarios(self, file_list):
for file in file_list:
self.scenarioList.append(Scenario(file))
def get_scenario(self):
self.currentScene = self.choose_scenario()
# todo: initialize the player here, probably should get this to happen on its own in the scenario
self.currentScene.initialize_player()
self.player = self.currentScene.get_player()
return self.currentScene
def choose_scenario(self):
if len(self.scenarioList) == 0:
return None
# scene = min(self.scenarioList, key=lambda x: abs(sum(x.get_weights()) - sum(self.player_model.values())))
scene = self.scenarioList[0]
# todo: re-enable when we have more scenes
# self.scenarioList.remove(scene)
return scene
def initialize_actions(self):
for i in range(self.history_length):
possible_actions = list(random.choices(self.action_choices, k=math.floor(random.uniform(1, 4))))
action = np.random.choice(list(self.player_model.keys()), p=list(self.player_model.values()))
possible_actions = (set(possible_actions) | {action})
self.action_history.append((action, possible_actions))
pass
def add_action(self, action, possible_actions):
if action in ["move", ""]:
action = "wait"
if action in self.action_choices or action == "wait":
self.action_history.append((action, possible_actions))
self.action_history = self.action_history[-self.history_length:]
pass
def update_model(self, command_array, possible_actions):
# update distraction timeout
if self.distraction_timeout <= 0:
self.distracted = False
if self.distracted:
self.distraction_timeout -= 1
# update action history
self.add_action(command_array[0], possible_actions)
# recalculate model
# self.calculate_model()
# ~~~ the new way? ~~~
# this gets the actual model, but we want an ordering?
# pprint(self.player.get_available_actions())
# exit(0)
self.calculate_probability_dict()
self.current_model, action_frequencies = self.calculate_probability_ordering()
# get available action
# available_actions = self.get_available_actions()
available_actions = self.player.get_available_actions()
# check against expected
difference = self.model_difference()
entropy = self.calculate_entropy()
# given those actions which other action is most probable?
distraction_list = self.get_action_prob(available_actions)
# test if ordering is correct given the past.
d = self.distribution_difference(action_frequencies)
sorted_d = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(sorted_d)
# exit(0)
good_distractions = sorted_d[0][0]
# we have a perceived preference ordering. that's the current model.
# given that preference
distraction_num = 0
# distraction_list = self.deploy_distraction()
# print(difference)
# debug: difference
# print("difference:", difference)
# print("entropy:", entropy)
self.large_threshold = self.large_threshold * .99
data = [difference, entropy, good_distractions, len(good_distractions)]
# data = [difference, entropy, distraction_list, distraction_num]
if difference is None or difference is np.nan:
print("this should never happen, you messed up chi-squared.")
return data, {"end": True, "distraction": False}
# if difference is big, update model and trigger path change attempt
if difference > self.large_threshold:
self.change_model()
self.path_change()
return data, {"end": True, "distraction": False}
# if difference is small, deploy distraction
if difference > self.small_threshold:
# add intervention/distraction task
if not self.distracted:
self.distracted = True
self.distraction_timeout = self.max_distraction_timeout
return data, {"end": False, "distraction": True}
# else continue on like normal.
return data, {"end": False, "distraction": False}
def distribution_difference(self, action_frequencies):
def powerset(iterable):
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))
available_actions = self.player.get_available_actions()
accepted_ordering = self.get_ordering_from_model(self.current_model)
action_additions = list(set(self.action_choices) - set(available_actions))
added_actions_scores = {}
base_case = {}
# todo: verify that the base case is always first
for added_actions in powerset(action_additions):
added_actions = list(added_actions)
added_actions_difference = 0
new_available_actions = available_actions + added_actions
for action_taken in new_available_actions:
# generate new things to add to
new_action_frequencies = copy.deepcopy(action_frequencies)
ordering_difference = 0
if added_actions or action_taken:
for action in available_actions:
if action_taken != action:
if (action_taken, action) in new_action_frequencies:
new_action_frequencies[(action_taken, action)] += 1
else:
new_action_frequencies[(action_taken, action)] = 1
for current_ordering in list(itertools.permutations(accepted_ordering)):
count_for = 0
count_against = 0
for action, count in new_action_frequencies.items():
if action[0] in current_ordering and action[1] in current_ordering:
if current_ordering.index(action[0]) < current_ordering.index(action[1]):
count_for += count
else:
count_against += count
# print(current_ordering, count_for, count_against+count_for)
# if the added actions is empty, store the result as a base case.
# else compare against base case
if not added_actions:
if count_against+count_for != 0:
base_case[current_ordering] = count_for/(count_against+count_for)
else:
if current_ordering not in base_case:
base_case[current_ordering] = 0
if count_for == 0:
count_against = 1
ordering_difference = abs(base_case[current_ordering] - count_for/(count_against+count_for))
# print(added_actions, ordering_difference)
if not added_actions:
break
else:
added_actions_difference += ordering_difference
if len(new_available_actions) != 0:
added_actions_scores[tuple(added_actions)] = added_actions_difference/len(new_available_actions)
# pprint(added_actions_scores)
return added_actions_scores
def calculate_model(self):
# ~~~the old way~~~
# based on the player action history, create a model, currently the relative frequency of all relevant actions
action_frequency = {action: 0 for action in self.action_choices}
for action, possible_actions in self.action_history:
# since we dont want to have a probability of something that isnt relevant, check it
if action in self.action_choices:
if action not in action_frequency:
action_frequency[action] = 0
action_frequency[action] += 1
for action in action_frequency:
if action_frequency[action] == 0:
action_frequency[action] += .0001
# get average
for action in action_frequency:
action_frequency[action] = action_frequency[action] / self.history_length
self.current_model = action_frequency
self.normalize_current_model()
# ~~~ end the old way ~~~
pass
def calculate_probability_dict(self):
self.action_prob_dict = {}
for action, key in self.action_history:
old = []
key = tuple(sorted(key))
if key in self.action_prob_dict:
old = self.action_prob_dict[key]
self.action_prob_dict[key] = [action] + old
def calculate_probability_ordering(self):
action_preference_frequency = {}
action_preference_totals = {}
for actions, good_actions in self.action_prob_dict.items():
for action in actions:
if len(actions) > 1:
for good_action in good_actions:
if action == good_action:
continue
# store a list of action preference
action_preference = (good_action, action)
if action_preference not in action_preference_frequency:
action_preference_frequency[action_preference] = 0
if good_action not in action_preference_totals:
action_preference_totals[good_action] = 0
action_preference_frequency[action_preference] += 1
action_preference_totals[good_action] += 1
pass
for action in self.action_choices:
if action not in action_preference_totals:
action_preference_totals[action] = 0
action_preference_totals.pop("wait", None)
# pprint(action_preference_totals)
# pprint(action_preference_frequency)
list_sum = sum(action_preference_totals.values())
if list_sum != 0:
for key, value in action_preference_totals.items():
action_preference_totals[key] = value / list_sum
# pprint(action_preference_totals)
# pprint(action_preference_frequency)
# pprint(self.current_model)
# exit(0)
return action_preference_totals, action_preference_frequency
def get_ordering_from_model(self, model):
# take in a model, output an ordering
ordering = [i[0] for i in sorted(model.items(), key=lambda kv: kv[1], reverse=True)]
return ordering
def calculate_entropy(self):
def sort_dict(dictionary): return [v for k, v in sorted(dictionary.items())]
current = sort_dict(self.current_model)
expected = sort_dict(self.player_model)
return scipy.stats.entropy(current, expected)
def model_difference(self):
# expected cant have 0's
def sort_dict(dictionary): return [v for k, v in sorted(dictionary.items())]
current = sort_dict(self.current_model)
expected = sort_dict(self.player_model)
# difference = scipy.spatial.distance.cityblock(current, expected)
difference = scipy.spatial.distance.cosine(current, expected)
# difference = scipy.spatial.distance.correlation(current, expected)
# difference, p = scipy.stats.chisquare(current, expected)
# print(difference)
return difference
def get_available_actions(self):
def expand_command(partial_command, player):
translation = {
"pickup": "onPickup",
"look": "onExamine",
"talk": "dialogue",
"use": "onUse"
}
if partial_command in translation:
event_type = translation[partial_command]
else:
return None
# room.get_entities? only the ones that are visible though
current_room = player.get_current_room()
all_entities = current_room.get_actors_visible() + current_room.get_items_visible()
random.shuffle(all_entities)
for entity in all_entities:
# special case for distractions
if entity.get_distractor() and entity.distraction_type == partial_command:
return partial_command + " " + entity.get_name()
# special case handling for dialogue
if event_type == "dialogue":
if type(entity) == Actor:
topics = list(entity.get_topics_list(player.get_keys()).values())
if topics is None or not topics:
continue
dialogue = random.choice(topics)
return partial_command + " " + entity.get_name() + " " + dialogue.get_topic()
continue
# non-examine events only work on Items
if event_type != "onExamine":
if type(entity) != Item:
continue
events = entity.get_events_type(event_type)
if not events:
continue
for event in events:
if event.check_allowed(player.get_keys()):
# check if the event is valid...
# if the text, and give and take keys are empty, its not a valid event
give, take = event.get_keys()
text = event.text
if text == "":
if give == [""] and take == [""]:
continue
return partial_command + " " + entity.get_name()
return None
available_actions = []
for command in ["pickup", "look", "talk", "use"]:
if expand_command(command, self.player) is not None:
available_actions.append(command)
return available_actions
def get_action_prob(self, available_actions=None):
if available_actions is None:
available_actions = self.action_choices
available_actions = set(available_actions)
action_closeness = {self.action_choices[x]: 0 for x in range(len(self.action_choices))}
for entry in self.action_history:
action_closeness[entry[0]] = (len(available_actions.intersection(set(entry[1])))+1) / (len(available_actions)+1)
for key in action_closeness:
action_closeness[key] /= len(self.action_history)
ordered_actions = sorted(self.action_choices, key=lambda x: action_closeness[x], reverse=True)
# pprint(self.action_history)
# pprint(available_actions)
# pprint(action_closeness)
# pprint(ordered_actions)
#
# exit(0)
return ordered_actions
# currently this just changes the player model to the action history calculated model,
# todo: in the future it should shift to an accepted quest path model.
def change_model(self):
self.player_model = copy.deepcopy(self.current_model)
# this should modify the player object to flag it for a path change.
def path_change(self):
# print("path change initiated!")
pass
# this should modify the player object to flag it with what the player should be attempted to be distracted with.
def deploy_distraction(self):
d1 = self.current_model
d2 = self.player_model
d3 = {key: abs(d1[key] - d2.get(key, 0)) for key in d1.keys()}
# print(d3)
sorted_keys = sorted(d3.items(), key=lambda kv: kv[1], reverse=True)
keys = [k[0] for k in sorted_keys]
return keys
# the rest of this shouldn't do anything useful for the player.
def reset_model(self):
# todo: get rid of redundancy
for action in self.action_choices:
self.player_model[action] = random.random()
self.player_model[action] = random.random()
self.quest_dist()
def set_model(self, player_model):
self.player_model = player_model
pass
def print_model(self):
print(self.player_model)
# todo: rewrite, it currently does jack shit
def trace_quests(self):
def ei(event_list):
return_string = ""
if event_list is None:
return ""
for event in event_list:
return_string += ",".join(event.whitelistKeys)
return_string += " | "
return_string += event.source_type
return_string += "->"
return_string += event.type
return_string += "->"
return_string += event.source_ID if event.source_ID is not None else ""
return_string += " | "
return_string += ",".join(event.giveKeys)
return_string += "\n\t"
return_string += event.text
return_string += "\n"
return return_string
def find_item_show(item: Item):
event_list = []
for event in self.currentScene.eventList:
for visible in event.makeVisible:
if item.name in visible[0] and event.room == item.start_room:
event_list.append(event)
return event_list
def find_keys(key):
# return key, unkey
return_list = []
for event in self.currentScene.eventList:
if key in event.giveKeys:
return_list.append(event)
return return_list
def pre_step(req_list):
return_list = []
for prereq in req_list:
if prereq.type == "onPickup":
new_list = find_item_show(prereq.source)
print(ei(new_list))
return_list += new_list
else:
for key in prereq.whitelistKeys:
new_list = find_keys(key)
print(ei(new_list))
return_list += new_list
return return_list
print("step================================================================")
prereq_list: List[Event] = find_keys("win")
print(ei(prereq_list))
print("step================================================================")
prereq_list = pre_step(prereq_list)
print("step================================================================")
prereq_list = pre_step(prereq_list)
print("step================================================================")
prereq_list = pre_step(prereq_list)
pass
# todo: rework this to actually tell if player is bored.
def quest_dist(self):
v = {'look': 0.3333333333333333,
'pickup': 0.3333333333333333,
'talk': 0.2666666666666666,
'use': 0.06666666666666667}
t = {'look': 0.000000000001,
'pickup': 0.23529411764705882,
'talk': 0.7058823529411765,
'use': 0.058823529411764705}
l = {'look': 0.3124, 'pickup': 0.3125, 'talk': 0.0001, 'use': 0.375}
r = {'look': random.random(),
'pickup': random.random(),
'talk': random.random(),
'use': random.random()}
self.player_model = r
self.normalize_player_model()
def normalize_player_model(self):
list_sum = sum(self.player_model.values())
for key, value in self.player_model.items():
self.player_model[key] = value / list_sum
def normalize_current_model(self):
list_sum = sum(self.current_model.values())
for key, value in self.current_model.items():
self.current_model[key] = value / list_sum
class Scenario:
roomList: Dict[str, Room]
eventList: List
dialogueList: List
actorList: List
itemList: List
start_location: str
jsonData: Dict
def __init__(self, file_name="example.json"):
with open(file_name) as f:
self.jsonData = json.load(f)
self.roomList = {}
self.actorList = []
self.itemList = []
self.eventList = []
self.start_location = "template"
self.dialogueList = []
self.room_compile()
self.link_builder()
self.player = None
def room_compile(self):
for room_json in self.jsonData["rooms"]:
name = room_json["name"]
if "startLocation" in room_json:
self.start_location = name
new_room = Room(
name,
room_json["desc"] if "desc" in room_json else "",
room_json["examineDesc"] if "examineDesc" in room_json else ""
)
if "items" in room_json:
for itemJSON in room_json["items"]:
new_room.add_item(self.item_create(itemJSON, new_room))
if "backgrounds" in room_json:
for itemJSON in room_json["backgrounds"]:
new_room.add_item(self.item_create(itemJSON, new_room))
if "actors" in room_json:
for actorJSON in room_json["actors"]:
new_room.add_actor(self.actor_create(actorJSON, new_room))
if "events" in room_json:
for eventJSON in room_json["events"]:
new_room.add_event(self.event_create(eventJSON, new_room, source_type="room", source=new_room))
# distractions need to be made for every type of thing that a player can get distracted by
for distract_type in ["look", "talk", "use", "pickup"]:
new_room.add_item(self.distraction_generation(new_room, distract_type))
self.roomList[name] = new_room
def link_builder(self):
for room_json in self.jsonData["rooms"]:
if "links" in room_json:
linking_room = self.roomList[room_json["name"]]
for linkJSON in room_json["links"]:
linking_room.add_link(self.roomList[linkJSON["roomName"]] if "roomName" in linkJSON else "template",
linkJSON["direction"] if "direction" in linkJSON else "up",
linkJSON["hidden"] if "hidden" in linkJSON else False)
def actor_create(self, actor_json, new_room):
new_actor = Actor(
actor_json["name"] if "name" in actor_json else "",
actor_json["examine"] if "examine" in actor_json else "",
actor_json["desc"] if "desc" in actor_json else "",
new_room
)
if new_actor.get_name() in ["template", ""]:
return None
if "events" in actor_json:
for eventJSON in actor_json["events"]:
new_actor.add_event(self.event_create(eventJSON, new_room, source_type="actor", source=new_actor))
if "hidden" in actor_json:
new_actor.hide()
if "dialogues" in actor_json:
for dialogueJSON in actor_json["dialogues"]:
new_dialogue = Dialogue(
dialogueJSON["whitelist"] if "whitelist" in dialogueJSON else "",
dialogueJSON["blacklist"] if "blacklist" in dialogueJSON else "",
dialogueJSON["key"] if "key" in dialogueJSON else "",
dialogueJSON["unkey"] if "unkey" in dialogueJSON else "",
dialogueJSON["keyRoom"] if "keyRoom" in dialogueJSON else [""],
dialogueJSON["unkeyRoom"] if "unkeyRoom" in dialogueJSON else [""],
dialogueJSON["text"] if "text" in dialogueJSON else "they stay silent",
dialogueJSON["topic"] if "topic" in dialogueJSON else "",
new_room
)
# get rid of empty entries.
for i in range(len(new_dialogue.whitelistKeys)):
if new_dialogue.whitelistKeys[i] == "":
new_dialogue.whitelistKeys.pop(i)
for i in range(len(new_dialogue.blacklistKeys)):
if new_dialogue.blacklistKeys[i] == "":
new_dialogue.blacklistKeys.pop(i)
new_actor.add_dialogue(new_dialogue)
self.eventList.append(new_dialogue)
self.actorList.append(new_actor)
return new_actor
def item_create(self, item_json, start_room):
new_item = Item(
item_json["name"] if "name" in item_json else "",
item_json["examine"] if "examine" in item_json else "",
item_json["invDesc"] if "invDesc" in item_json else "",
item_json["desc"] if "desc" in item_json else "",
item_json["weight"] if "weight" in item_json else 0.0,
item_json["smell"] if "smell" in item_json else "",
item_json["taste"] if "taste" in item_json else "",
item_json["size"] if "size" in item_json else "",
item_json["pickupable"] if "pickupable" in item_json else False,
item_json["pickupKey"] if "pickupKey" in item_json else "",
start_room
)
# get rid of templates
if new_item.get_name() in ["template", ""]:
return None
if "events" in item_json:
for eventJSON in item_json["events"]:
new_item.add_event(self.event_create(eventJSON, start_room, source_type="item", source=new_item))
if "hidden" in item_json:
new_item.hide()
self.itemList.append(new_item)
return new_item
def background_create(self, item_json, start_room):
new_item = Background(
item_json["name"] if "name" in item_json else "",
item_json["examine"] if "examine" in item_json else "",
item_json["invDesc"] if "invDesc" in item_json else "",
item_json["desc"] if "desc" in item_json else "",
item_json["weight"] if "weight" in item_json else 0.0,
item_json["smell"] if "smell" in item_json else "",
item_json["taste"] if "taste" in item_json else "",
item_json["size"] if "size" in item_json else "",
start_room
)
# get rid of templates
if new_item.get_name() in ["template", ""]:
return None
if "hidden" in item_json:
new_item.hide()
self.itemList.append(new_item)
return new_item
def event_create(self, event_json, room, source_type=None, source=None):
new_event = Event(
event_json["whitelist"] if "whitelist" in event_json else "",
event_json["blacklist"] if "blacklist" in event_json else "",
event_json["key"] if "key" in event_json else [""],
event_json["unkey"] if "unkey" in event_json else [""],
event_json["keyRoom"] if "keyRoom" in event_json else [""],
event_json["unkeyRoom"] if "unkeyRoom" in event_json else [""],
event_json["text"] if "text" in event_json else "",
event_json["type"] if "type" in event_json else "",
room,
source_type=source_type,
source=source
)
# todo: instead of finding things by name later, find them now and store reference instead of name.
if "show" in event_json:
for visibleJSON in event_json["show"]:
new_event.add_show([
visibleJSON["name"] if "name" in visibleJSON else "",
visibleJSON["class"] if "class" in visibleJSON else ""
])
if "hide" in event_json:
for visibleJSON in event_json["hide"]:
new_event.add_hide([
visibleJSON["name"] if "name" in visibleJSON else "",
visibleJSON["class"] if "class" in visibleJSON else ""
])
# remove blank keys
for i in range(len(new_event.whitelistKeys)):
if new_event.whitelistKeys[i] == "":
new_event.whitelistKeys.pop(i)
for i in range(len(new_event.blacklistKeys)):
if new_event.blacklistKeys[i] == "":
new_event.blacklistKeys.pop(i)
self.eventList.append(new_event)
return new_event
def distraction_generation(self, room, distraction_type):
# get a list of distractions
new_item = Background(
"distraction: type " + distraction_type,
"aha you got distracted!",
"aha you got distracted!",
"aha you got distracted!",
0,
"aha you got distracted!",
"aha you got distracted!",
"aha you got distracted!",
room
)
new_item.set_distractor(True, distraction_type)
new_item.hide()
self.itemList.append(new_item)
return new_item
pass
def get_weights(self):
return self.jsonData["weights"] if "weights" in self.jsonData else [0, 0, 0, 0, 0]
def initialize_player(self):
map_chart = self.jsonData["map"] if "map" in self.jsonData else "you have no map"
starting_keys = self.jsonData["startingKeys"] if "startingKeys" in self.jsonData else []
player = Player(self.roomList[self.start_location], starting_keys, map_chart)
player.add_gold(self.jsonData["initialGold"] if "initialGold" in self.jsonData else 0)
self.player = player
def get_player(self):
return self.player
class Display:
player: Player
display_width = 150
print_list: List[List[str]]