-
Notifications
You must be signed in to change notification settings - Fork 3
/
core.py
1396 lines (1140 loc) · 51.5 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import time
import sys
import numpy as np
from collections import namedtuple, defaultdict
from queue import PriorityQueue
import pickle
# import minihack
import nle.nethack as nh
np.set_printoptions(threshold=sys.maxsize)
class Saver:
def __init__(self, obs_keys, filename):
self.trajectory = defaultdict(list)
self.filename = filename
self.obs_keys = obs_keys
def save_obs_and_action(self, observation, action):
for k in self.obs_keys:
self.trajectory[k].append(observation[k])
self.trajectory['actions'].append(action)
def save_to_file(self):
with open(self.filename+'.pkl', 'wb') as fp:
pickle.dump(self.trajectory, fp)
print(f'Trajectory saved to {self.filename}')
Inventory = namedtuple('Inventory', 'letters classes glyphs descs')
BLStats = namedtuple('BLStats', 'x y strength_percentage strength dexterity constitution intelligence wisdom charisma score hitpoints max_hitpoints depth gold energy max_energy armor_class monster_level experience_level experience_points time hunger_state carrying_capacity dungeon_number level_number prop_mask align')
class GameWhisperer:
def __init__(self, env, fast_mode, saver, filename):
try:
from game_items.item_manager_sk import Item_manager_sk
self.item_manager = Item_manager_sk('game_items/objects.pl')
except Exception:
print("pyswip or prolog is not present, in-game item management is disabled")
self.env = env
self.a_yx = [-1, -1]
self.walkable_glyphs = [(x, -1) for x in b'!"$%()*./<=>?[\\]`u'] + \
[(x, 7) for x in b'#df'] + \
[(x, 15) for x in b'#@df'] + \
[(x, 3) for x in b'-|']
self.size_y = 21
self.size_x = 79
self.current_obs = self.env.reset()
self.glyph_obs = self.current_obs['glyphs']
self.char_obs = self.current_obs['chars']
self.color_obs = self.current_obs['colors']
self.message = self.current_obs['message']
self.update_inv()
self.parsed_message = self.parse_message()
if 'tty_chars' in self.current_obs.keys():
self.all_obs = self.current_obs['tty_chars']
self.bl_stats = BLStats(*self.current_obs['blstats'])
self.memory = [[-1 for _ in range(self.size_x)] for _ in range(self.size_y)]
self.exception = []
self.search_map = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
self.risk_map = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
self.last_risk_update = 0
self.act_num = 0
self.score = 0
self.total_score = 0
self.cooldown = 100000
self.default_search_max = 10
self.default_hard_search_max = 10
self.search_max = self.default_search_max
self.hard_search_max = self.default_hard_search_max
self.agent_id = -1
self.update_agent()
self.agent_id = self.glyph_obs[self.a_yx[0]][self.a_yx[1]]
self.memory[self.a_yx[0]][self.a_yx[1]] = self.act_num
self.safe_play = False
self.strict_safe_play = False # when the strategy provides for strict safety
self.recently_ejected = False
self.last_monster_searched = (-1, -1, 0)
self.monster_exception = []
self.engraved_tiles = []
self.inedible = []
self.recently_killed = []
self.shop_tiles = []
self.last_pray = -1
self.old_turn = 0
self.new_turn = 0
self.panic = False
self.pet_alive = False
self.pet_alive_turn = 0
self.ran = False
self.ran_turn = 0
self.ran_cooldown = 2
self.guard_encounter = 0
self.u_stairs_locations = []
self.d_stairs_locations = []
self.tactical_descent = 0
self.fast_mode = fast_mode
self.stuck_counter = 0
self.hard_search_num = 0
self.elbereth_violated = 0
self.depth_turns = {}
self.saver = saver
# if not self.fast_mode:
# env.render()
def calculate_risk(self, y, x):
"""
function that calculates the risk value of a set of tiles
given the location of a hazard.
+1 +1 +1 +1 +1
+1 +2 +2 +2 +1
+1 +2 +3 +2 +1 hazard on the center
+1 +2 +2 +2 +1
+1 +1 +1 +1 +1
:param y: dangerous tile y/vertical value
:param x: dangerous tile x/horizontal value
"""
touched = []
layer = self.neighbors_8_dir(y, x)
self.risk_map[y][x] += 2
for tile in layer:
self.risk_map[tile[0]][tile[1]] += 2
touched.append((tile[0], tile[1]))
for tile in layer:
second_layer = self.neighbors_8_dir(tile[0], tile[1])
for s_tile in second_layer:
if not touched.__contains__((s_tile[0], s_tile[1])):
self.risk_map[s_tile[0]][s_tile[1]] += 1
touched.append((s_tile[0], s_tile[1]))
def update_riskmap(self):
"""
function that calculates the risk value of every tile
"""
self.risk_map = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
for y in range(self.size_y):
for x in range(self.size_x):
if self.is_a_monster(y, x):
self.calculate_risk(y, x)
def update_inv(self):
self.inv_obs = Inventory(
self.current_obs['inv_letters'],
self.current_obs['inv_oclasses'],
self.current_obs['inv_glyphs'],
self.current_obs['inv_strs'])
def update_obs(self):
"""
function that update every possible version of the observation space
"""
self.glyph_obs = self.current_obs['glyphs']
self.char_obs = self.current_obs['chars']
self.color_obs = self.current_obs['colors']
self.message = self.current_obs['message']
self.update_inv()
self.parsed_message = self.parse_message()
self.bl_stats = BLStats(*self.current_obs['blstats'])
if 'tty_chars' in self.current_obs.keys():
self.all_obs = self.current_obs['tty_chars']
if self.last_risk_update != self.bl_stats.time:
self.update_riskmap()
self.last_risk_update = self.bl_stats.time
def crop_printer(self, obs):
"""
debug function that print a cropped (on the agent)
version of a given observation space
:param obs: given observation space
"""
for i in range(-2, 3):
print(" ".join(str(obs[self.a_yx[0] + i][self.a_yx[1] + j]) for j in range(-2,3)))
def debug_crop(self):
"""
debug function that print a cropped (on the agent)
version of every observation space
"""
self.crop_printer(self.char_obs)
self.crop_printer(self.color_obs)
self.crop_printer(self.glyph_obs)
print(self.exception)
def glyph_cooldown(self, glyph):
"""
function that calculates the cooldown for taking
into account a given glyph
:param glyph: given glyph
"""
if self.recently_ejected:
self.recently_ejected = False
return -1
char = glyph[0]
color = glyph[1]
cooldown = self.cooldown
if char == 64 and color == 15:
cooldown = -1
elif char == 43 and color == 3:
cooldown = 50
elif char == 45 or char == 124 and color == 3:
cooldown = 200
elif char == 62 or char == 36 or char == 60:
cooldown = 15
elif char == 37:
cooldown = 1
elif [58, 59, 38, 44].__contains__(char) or 65 <= char <= 90 or 97 <= char <= 122:
cooldown = 5
return cooldown
def find(self, condition, args):
"""
function for searching the closest tile which satisfies a given condition
starting from the agent position
:param condition: condition function to consider
:param args: arguments for the given condition
"""
frontier = list()
looked_mat = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
current = (self.a_yx[0], self.a_yx[1])
found = False
while current is not None and not found:
looked_mat[current[0]][current[1]] = 1
if condition(current, args):
return True, current[0], current[1]
nbh = self.neighbors_8_dir(current[0], current[1])
for next_tile in nbh:
if looked_mat[next_tile[0]][next_tile[1]] == 0 and not frontier.__contains__(next_tile):
frontier.append(next_tile)
if len(frontier) > 0:
current = frontier.pop(0)
else:
current = None
return False, -1, -1
def find_far(self, condition):
"""
function for searching the farest tile which satisfies a given condition
:param condition: condition function to consider
"""
frontier = list()
looked_mat = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
current = (self.a_yx[0], self.a_yx[1])
best = None
while current is not None:
looked_mat[current[0]][current[1]] = 1
if condition(current[0], current[1]):
best = current
nbh = self.neighbors_8_dir(current[0], current[1])
for next_tile in nbh:
if looked_mat[next_tile[0]][next_tile[1]] == 0 and next_tile not in frontier:
frontier.append(next_tile)
if len(frontier) > 0:
current = frontier.pop(0)
else:
current = None
if best is not None:
return True, best[0], best[1]
else:
return False, -1, -1
def condition_agent_obj(self, tile, args):
"""
condition function for searching the agent on the map
:param tile: tile to verify
:param args: arguments for the given condition
:return TRUE -> if condition is verified, FALSE -> elsewise
"""
if args.__contains__((self.char_obs[tile[0]][tile[1]], self.color_obs[tile[0]][tile[1]])) and \
(self.memory[tile[0]][tile[1]] == -1 or
abs(self.memory[tile[0]][tile[1]] - self.act_num) > self.glyph_cooldown(
(self.char_obs[tile[0]][tile[1]], self.color_obs[tile[0]][tile[1]]))) \
and (self.agent_id == self.glyph_obs[tile[0]][tile[1]] or self.agent_id == -1):
return True
else:
return False
def update_agent(self):
"""
function for updating the known agent's position
"""
found_agent, self.a_yx[0], self.a_yx[1] = self.find(self.condition_agent_obj, [(64, 15)])
return found_agent
def hard_search(self):
"""
function to set the "hard search", iteratively decreasing
the number of total searches allowed per tile, after resetting the searchmap
"""
self.search_map = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
self.search_max = self.hard_search_max
self.hard_search_max -= 1
def reset_memory(self):
"""
function that resets the agent's knowledge of the game world
"""
self.exception = []
self.monster_exception = []
self.search_max = self.default_search_max
self.hard_search_max = self.default_hard_search_max
self.memory = [[-1 for _ in range(self.size_x)] for _ in range(self.size_y)]
self.search_map = [[0 for _ in range(self.size_x)] for _ in range(self.size_y)]
def unexplored_walkable_around(self, y, x):
"""
function that checks for the presence of
never visited and walkable tiles around the agent
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if exist a near walkable and unexplored tile, FALSE -> elsewise
"""
walkable = 0
unex_walkable = 0
door_flag = False
for i in self.neighbors_8_dir(y, x):
if self.is_doorway(i[0], i[1]):
door_flag = True
if self.char_obs[i[0]][i[1]] == 43 or self.char_obs[i[0]][i[1]] == 96:
return True
if self.is_a_monster(i[0], i[1]):
return True
if self.is_walkable(i[0], i[1]):
walkable += 1
if self.is_walkable(i[0], i[1]) and self.is_unexplored(i[0], i[1]):
unex_walkable += 1
if door_flag and walkable == 1 and unex_walkable == 0:
return False
if door_flag:
return True
if walkable >= 3 or unex_walkable >= 1:
return True
return False
def is_unexplored(self, y, x):
"""
function that checks if a given tile is unexplored
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is unexplored, FALSE -> elsewise
"""
if self.memory[y][x] == -1 or abs(self.memory[y][x] - self.act_num) >= self.cooldown:
return True
else:
return False
def is_walkable(self, y, x):
"""
function that checks if a given tile is walkable
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is walkable, FALSE -> elsewise
"""
char = self.char_obs[y][x]
color = self.color_obs[y][x]
if char == 64 and (y != self.a_yx[0] or x != self.a_yx[1]):
return False
if self.shop_tiles.__contains__((y, x)):
return False
if char == 101 and not self.panic: # spore or eye
return False
elif char == 70 and color != 10 and color != 5 and not self.panic and self.bl_stats.hitpoints < 15: # Molds
return False
# elif char == 98 and color == 2 and not self.panic: # Acid Blob
# return False
if char == 43 and color != 3:
return True
if (self.walkable_glyphs.__contains__((char, color)) or self.walkable_glyphs.__contains__(
(char, -1))) and not self.exception.__contains__((y, x)):
if char == 64 and (self.glyph_obs[y][x] != self.agent_id or color != 15):
return False
return True
else:
return False
def is_a_monster(self, y, x):
"""
function that checks if a given tile is a monster
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is a monster, FALSE -> elsewise
"""
char = self.char_obs[y][x]
color = self.color_obs[y][x]
if self.monster_exception.__contains__((y, x)):
return False
# if char == 104 and self.bl_stats.depth >= 3:
# return False
if char == ord('@') and color != 15:
return True
if char in b":;&'," or 65 <= char <= 90 or 97 <= char <= 122:
#if self.is_pet(char, color)
if (char in b"fd") and (
color == 7 or color == 15) and self.pet_alive: # or (find and self.is_unexplored(y, x)):
return False
elif char == ord('u') and color == 3 and self.pet_alive: # tamed pony is not a moster
return False
elif char == ord('e') and not self.panic and self.stuck_counter < 100: # spore or eye
return False
elif char == ord('F') and color != 10 and color != 5 and not self.panic and self.bl_stats.hitpoints < 15: # Molds
return False
# elif char == 98 and color == 2 and not self.panic: # Acid Blob
# return False
else:
return True
else:
return False
def is_passive_monster(self, y, x):
"""
function that checks if a given tile is a passive monster
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is a monster, FALSE -> elsewise
"""
char = self.char_obs[y][x]
color = self.color_obs[y][x]
if char in b"bcePRF@":
return True
else:
return False
def is_safe(self, y, x):
"""
function that checks if a given tile is safe (with zero risk)
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is safe, FALSE -> elsewise
"""
if self.risk_map[y][x] > 0:
return False
else:
return True
def is_unsearched_wallside(self, y, x):
"""
function that checks if a given tile is near a wall
and the agent never performed a search action there
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is unsearched and wallside, FALSE -> elsewise
"""
for (nhb_y, nhb_x) in self.neighbors_4_dir(y, x):
if (self.char_obs[nhb_y][nhb_x] == 124 or self.char_obs[nhb_y][nhb_x] == 45) and \
self.color_obs[nhb_y][nhb_x] == 7 and self.search_map[nhb_y][nhb_x] == 0:
return True
return False
def is_unsearched_voidside(self, y, x):
"""
function that checks if a given tile is near a black unknown tile
and the agent never performed a search action there
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is unsearched and near an unknown tile, FALSE -> elsewise
"""
for (nhb_y, nhb_x) in self.neighbors_4_dir(y, x):
if self.char_obs[nhb_y][nhb_x] == 32 and self.search_map[nhb_y][nhb_x] == 0:
return True
return False
def is_doorway(self, y, x):
"""
function that checks if a given tile is a doorway looking for the glyph and also
counting the walls around the tile
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is a doorway, FALSE -> elsewise
"""
char = self.char_obs[y][x]
color = self.color_obs[y][x]
if char in b'+|-' and color == 3: # or (char == 46 and self.is_unexplored(y, x)): wip
return True
walls_count_h = 0
walls_count_v = 0
for (nhb_y, nhb_x) in self.neighbors_4_dir(y,x):
if self.char_obs[nhb_y][nhb_x] in b"|-" and self.color_obs[nhb_y][nhb_x] == 7:
if nhb_x == x: # if vertically adjacent
walls_count_v += 1
else:
walls_count_h += 1
if walls_count_h == 2 or walls_count_v == 2:
return True
else:
return False
def is_isolated(self, y, x, glyph, cross):
"""
function that checks if a given tile is isolated from
other tiles of the same kind (or also near a doorway)
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: TRUE -> if given tile is isolated, FALSE -> elsewise
"""
same_glyph_count = 0
near = self.neighbors_8_dir(y, x)
while len(near) > 0:
next_tile = near.pop()
if cross and next_tile[0] != y and next_tile[1] != x:
continue
if glyph is None:
if self.glyph_obs[next_tile[0]][next_tile[1]] == self.glyph_obs[y][x] or self.is_doorway(next_tile[0], next_tile[1]):
same_glyph_count += 1
else:
char = glyph[0]
color = glyph[1]
if (self.char_obs[next_tile[0]][next_tile[1]] == char and self.color_obs[next_tile[0]][
next_tile[1]] == color) or self.is_doorway(next_tile[0], next_tile[1]):
same_glyph_count += 1
if same_glyph_count < 2:
return True
else:
return False
def is_near_glyph(self, y, x, glyph, dir_num):
"""
function that checks if a given tile is near
a tile carrying a specific glyph
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:param glyph: specific glyph to be noticed
:param dir_num: 4 or 8 directions to check
:return: TRUE -> if given tile is near the given glyph, FALSE -> elsewise
"""
char = glyph[0]
color = glyph[1]
around_it = []
if dir_num == 8:
around_it = self.neighbors_8_dir(y, x)
if dir_num == 4:
around_it = self.neighbors_4_dir(y, x)
while len(around_it) > 0:
near = around_it.pop()
if self.char_obs[near[0]][near[1]] == char and (self.color_obs[near[0]][near[1]] == color or color == -1):
return True
return False
def neighbors_8_dir(self, y, x):
"""
function that return the 8-directions neighborhood of a given tile
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: a list containing the 8 tiles around the given one
"""
neighborhood = self.neighbors_4_dir(y, x)
if y > 0:
if x > 0:
neighborhood.append((y - 1, x - 1)) # nw
if x < self.size_x - 1:
neighborhood.append((y - 1, x + 1)) # ne
if x < self.size_x - 1:
if y < self.size_y - 1:
neighborhood.append((y + 1, x + 1)) # se
if y < self.size_y - 1:
if x > 0:
neighborhood.append((y + 1, x - 1)) # sw
return neighborhood
def neighbors_4_dir(self, y, x):
"""
function that return the 4-directions (N,E,S,W) neighborhood of a given tile
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:return: a list containing the 4 tiles around the given one
"""
neighborhood = list()
if y > 0:
neighborhood.append((y - 1, x)) # n
if x < self.size_x - 1:
neighborhood.append((y, x + 1)) # e
if y < self.size_y - 1:
neighborhood.append((y + 1, x)) # s
if x > 0:
neighborhood.append((y, x - 1)) # w
return neighborhood
def neighbors(self, y, x, safe):
"""
function that returns the list of correctly reachable tiles
(considering walkable tiles without entering the doors diagonally)
starting from a given tile, avoiding dangerous tiles in case the "safe" flag is active
:param y: tile y/vertical coordinate
:param x: tile x/horiziontal coordinate
:param safe: flag that determines the consideration of dangerous tiles
:return: a list containing the tiles around the given one
"""
neighborhood = list()
doorway = self.is_doorway(y, x)
for (nhb_y, nhb_x) in self.neighbors_8_dir(y,x):
if self.is_walkable(nhb_y, nhb_x) and (not safe or self.is_safe(nhb_y, nhb_x)) and \
(nhb_x == x or nhb_y == y or not (doorway or self.is_doorway(nhb_y, nhb_x))): #not diagonally adjacent or no doors in the way
neighborhood.append((nhb_y, nhb_x))
return neighborhood
def parse_message(self):
"""
function that parse the in game message form the NLE observation
:return: a string containing the parsed message
"""
return bytes(self.message).decode().strip('\0')
def parse_all(self):
"""
function that parse the complete observation returning a readable form of it
:return: a string containing the parsed observation state
"""
parsed_string = ""
for i in range(0, 24):
for j in range(0, 80):
c = self.all_obs[i][j]
parsed_string = parsed_string + chr(c)
return parsed_string
def type_text(self, text):
for k in text:
self.current_obs, rew, done, info = self.env.step(nh.ACTIONS.index(ord(k)))
return rew, done, info
# new version, tested
def do_it(self, action, action_iterable=None):
"""
function for sending input to the game terminal.
It offers the management of specific cases, automating some actions.
:param action: action to be performed. Must be a character or an action in nle.nethack.ACTIONS
:param action_iterable: optional iterable useful when other actions have to be performed
:return: the "reward" value (1 if episode success, 0 elsewise),
the "done" value (TRUE if the episode endend, FALSE elsewise),
the "info" object containg extra information (Gym standard implementation)
"""
# print(self.bl_stats)
self.old_turn = self.bl_stats.time
rew = 0
done = False
info = None
if self.update_agent():
self.current_obs, rew, done, info = self.env.step(38)
self.update_obs()
# observations.append(numpy.concatenate((game.current_obs['chars'], game.current_obs['colors']), axis=None))
def to_action_index(action):
if isinstance(action, str):
assert len(action) == 1, action
action = ord(action)
return nh.ACTIONS.index(action)
rew, done, info = self.single_step(to_action_index(action))
if action_iterable:
for a in action_iterable:
rew, done, info = self.single_step(to_action_index(a))
return rew, done, info
def single_step(self, action_index):
"""
function for sending a single input to the game terminal.
It offers the management of specific cases, automating some actions.
:param action_index: action to be performed. Must be the index of the action in nle.nethack.ACTION
:return: the "reward" value (1 if episode success, 0 elsewise),
the "done" value (TRUE if the episode endend, FALSE elsewise),
the "info" object containg extra information (Gym standard implementation)
"""
rew = 0
done = False
info = None
if not self.fast_mode:
print("pray_timeout: ", abs(self.last_pray - self.bl_stats.time))
if self.bl_stats.time % 100 == 0:
print("current score: ", self.bl_stats.score, " turn: ",
self.bl_stats.time, " time: ", time.localtime()[3], ":", time.localtime()[4], " -")
go_back(2)
if abs(self.bl_stats.time - self.pet_alive_turn) > 10 and self.bl_stats.time > 2000:
self.pet_alive = False
if self.act_num % 50 == 0: # modifica
self.panic = False
if self.ran:
if abs(self.ran_turn - self.bl_stats.time) > self.ran_cooldown:
self.ran = False
if self.score < self.bl_stats.score:
self.score = self.bl_stats.score
if self.parsed_message.__contains__("Hello stranger, who are you?"): # respond Croesus
self.guard_encounter += 1
return -1, True, None
'''
if self.update_agent():
self.current_obs, rew, done, info = self.env.step(38)
self.update_obs()
'''
if self.update_agent():
self.current_obs, rew, done, info = self.env.step(action_index)
self.update_obs()
if "swap" in self.parsed_message:
self.pet_alive = True
self.pet_alive_turn = self.bl_stats.time
if self.parsed_message.__contains__("Are you sure you want to pray?") or self.parsed_message.__contains__(
"Really attack"):
self.type_text("y")
if self.parsed_message.__contains__("You are carrying too much to get through."):
next_tile = self.inverse_move_translator(self.a_yx[0], self.a_yx[1], action_index)
self.exception.append(next_tile)
self.update_obs()
if self.parsed_message.__contains__("Closed for inventory"):
for ty, tx in self.neighbors_4_dir(self.a_yx[0], self.a_yx[1]):
if self.char_obs[ty][tx] == ord('+') and self.color_obs[ty][tx] == 3:
self.shop_tiles.append((ty, tx))
if ((self.parsed_message.__contains__("Welcome") and self.parsed_message.__contains__(
"\"")) or self.parsed_message.__contains__("\"How dare you break my door?\"")) \
and not 0 <= self.bl_stats.time <= 5:
self.shop_propagation(self.a_yx)
if self.bl_stats.max_hitpoints != 0 and (self.bl_stats.hitpoints / self.bl_stats.max_hitpoints) <= 0.5 and not self.safe_play:
if not self.fast_mode:
print("SAFE_MODE : enabled")
self.safe_play = True
elif self.bl_stats.max_hitpoints != 0 and (self.bl_stats.hitpoints / self.bl_stats.max_hitpoints) > 0.85 and self.safe_play:
if not self.fast_mode:
print("SAFE_MODE : disabled")
self.safe_play = False
self.act_num += 1
if self.update_agent():
self.memory[self.a_yx[0]][self.a_yx[1]] = self.act_num
if nh.ACTIONS[action_index] == nh.Command.SEARCH:
self.search_map[self.a_yx[0]][self.a_yx[1]] = 1
for next_tile in self.neighbors_8_dir(self.a_yx[0], self.a_yx[1]):
self.search_map[next_tile[0]][next_tile[1]] = 1
if not self.fast_mode: # and x != 10:
# go_back(27)
self.env.render()
# time.sleep(0.05)
if self.saver:
self.saver.save_obs_and_action(self.current_obs, action_index)
self.new_turn = self.bl_stats.time
self.depth_turns.setdefault(str(self.bl_stats.depth), 0)
self.depth_turns[str(self.bl_stats.depth)] += abs(self.old_turn - self.new_turn)
return rew, done, info
def shop_propagation(self, tile):
"""
function that propagates the "shop" status to the appropriate tiles starting from the given tile
:param tile: the starting tile
:return: //
"""
for near in self.neighbors_8_dir(tile[0], tile[1]):
char = self.char_obs[near[0]][near[1]]
if char in b'|-# ' or (
near[0] == self.a_yx[0] and near[1] == self.a_yx[
1]): # or ([58,59,38,39,44].__contains__(char) or 65 <= char <= 90 or 97 <= char <= 122) :
continue
elif not self.shop_tiles.__contains__(near):
self.shop_tiles.append(near)
self.shop_propagation(near)
@staticmethod
def move_translator(from_y, from_x, to_y, to_x):
"""
function that calculates the move according to the NLE implementation
needed to move between two given tiles
:param from_x: x value of the starting tile
:param from_y: y value of the starting tile
:param to_x: x value of the destination tile
:param to_y: y value of the destination tile
:return: the numerical value of the action to be performed
"""
if to_y > from_y: # la y del next è maggiore -> movimenti verso sud
if to_x > from_x:
move = nh.CompassDirection.SE
elif to_x == from_x:
move = nh.CompassDirection.S
else:
move = nh.CompassDirection.SW
elif to_y == from_y: # la y del next è uguale -> movimenti verso est ed ovest
if to_x > from_x:
move = nh.CompassDirection.E # e
else:
move = nh.CompassDirection.W # w
else: # la y del next è minore -> movimenti verso nord
if to_x > from_x:
move = nh.CompassDirection.NE # ne
elif to_x == from_x:
move = nh.CompassDirection.N # n
else:
move = nh.CompassDirection.NW # nw
return move
@staticmethod
def inverse_move_translator(from_y, from_x, direction):
"""
function that calculates the destination tile given
a starting tile and a direction (according to the NLE implementation)
:param from_x: x value of the starting tile
:param from_y: y value of the starting tile
:param direction: the move according to the NLE implementation
:return: y and x value of the destination tile
"""
if direction == nh.CompassDirection.N:
return from_y - 1, from_x
elif direction == nh.CompassDirection.NE:
return from_y - 1, from_x + 1
elif direction == nh.CompassDirection.E:
return from_y, from_x + 1
elif direction == nh.CompassDirection.SE:
return from_y + 1, from_x + 1
elif direction == nh.CompassDirection.S:
return from_y + 1, from_x
elif direction == nh.CompassDirection.SW:
return from_y + 1, from_x - 1
elif direction == nh.CompassDirection.W:
return from_y, from_x - 1
elif direction == nh.CompassDirection.NW:
return from_y - 1, from_x - 1
def reset_game(self):
"""
function that sets variable values to their initial version,
preparing the agent for a new game
:return: //
"""
self.current_obs = self.env.reset()
self.new_turn = 0
self.elbereth_violated = 0
self.old_turn = 0
self.update_obs()
self.reset_memory()
self.safe_play = False
self.agent_id = -1
self.update_agent()
self.agent_id = self.glyph_obs[self.a_yx[0]][self.a_yx[1]]
self.memory[self.a_yx[0]][self.a_yx[1]] = self.act_num
if not self.fast_mode:
self.env.render()
self.engraved_tiles = []
self.inedible = []
self.shop_tiles = []
self.u_stairs_locations = []
self.d_stairs_locations = []
self.tactical_descent = 0
self.total_score += self.score
self.score = 0
self.recently_killed = []
self.depth_turns = {}
self.last_pray = -1
def partial_reset_game(self):
"""
function that sets some variable values to their initial version,
resetting the agent's knowledge of the world
:return: //
"""
self.pet_alive = False
self.update_obs()
self.reset_memory()
self.engraved_tiles = []
self.recently_killed = []
self.shop_tiles = []
self.inedible = []
def get_items_by_class(self, oc_class):
return (i for i,c in enumerate(self.inv_obs.classes) if c == oc_class)
def get_elbereth_violation(self):
return self.elbereth_violated
def set_elbereth_violation(self):
self.elbereth_violated = self.act_num
def check_exception(self, tile):
return self.exception.__contains__((tile[0], tile[1]))
def append_exception(self, tile):
self.exception.append(tile)
def check_engraved(self, tile):
return self.engraved_tiles.__contains__((tile[0], tile[1]))
def append_engraved(self, tile):
self.engraved_tiles.append(tile)
def check_monster_exception(self, tile):
return self.monster_exception.__contains__((tile[0], tile[1]))
def append_monster_exception(self, tile):
self.monster_exception.append(tile)
def check_inedible(self, tile):
return self.inedible.__contains__((tile[0], tile[1]))
def append_inedible(self, tile):
self.inedible.append(tile)
def reset_inedible(self):
self.inedible = []
def get_recently_killed(self):
return self.recently_killed
def append_recently_killed(self, data):