-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
291 lines (250 loc) · 9.38 KB
/
utils.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
import numpy as np
import gym
import math
import IPython.display as display
import time
import matplotlib.pyplot as plt
from matplotlib.image import AxesImage
from typing import Callable,Tuple, List
from nle import nethack
from minihack import LevelGenerator
MOVEMENT_ACTIONS = tuple(nethack.CompassDirection)
OTHER_ACTIONS = MOVEMENT_ACTIONS + (
nethack.Command.PICKUP,
nethack.Command.WIELD,
nethack.Command.FIRE
)
def get_player_location(game_map: np.ndarray, symbol : str = "@") -> Tuple[int, int]:
x, y = np.where(game_map == ord(symbol))
return (x[0], y[0])
def get_target_location(game_map: np.ndarray, symbol : str = ">") -> Tuple[int, int]:
x, y = np.where(game_map == ord(symbol))
return (x[0], y[0])
def get_monster_location(game_map: np.ndarray) -> List[Tuple[int, int]]:
symbols_monster = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWQXYZ':;&~_]"
coord_monsters = []
for symbol in symbols_monster:
x, y = np.where(game_map == ord(symbol))
coord_monsters.extend(list(zip(x, y)))
return coord_monsters
def get_weapon_location(game_map: np.ndarray) -> List[Tuple[int, int]]:
weapons_symbols = ")"
coord_weapons = []
for symbol in weapons_symbols:
x, y = np.where(game_map == ord(symbol))
coord_weapons.extend(list(zip(x, y)))
return coord_weapons
def is_wall(position_element: int) -> bool:
obstacles = "|- "
return chr(position_element) in obstacles
def get_valid_moves(game_map: np.ndarray, current_position: Tuple[int, int]) -> List[Tuple[int, int]]:
x_limit, y_limit = game_map.shape
valid = []
x, y = current_position
# North
if y - 1 > 0 and not is_wall(game_map[x, y-1]):
valid.append((x, y-1))
# East
if x + 1 < x_limit and not is_wall(game_map[x+1, y]):
valid.append((x+1, y))
# South
if y + 1 < y_limit and not is_wall(game_map[x, y+1]):
valid.append((x, y+1))
# West
if x - 1 > 0 and not is_wall(game_map[x-1, y]):
valid.append((x-1, y))
if x - 1 > 0 and y - 1 > 0 and not is_wall(game_map[x-1, y-1]):
valid.append((x-1, y-1))
if x + 1 > 0 and y + 1 > 0 and not is_wall(game_map[x+1, y+1]):
valid.append((x+1, y+1))
if x + 1 > 0 and y - 1 > 0 and not is_wall(game_map[x+1, y-1]):
valid.append((x+1, y-1))
if x - 1 > 0 and y + 1 > 0 and not is_wall(game_map[x-1, y+1]):
valid.append((x-1, y+1))
return valid
def actions_from_path(start: Tuple[int, int], path: List[Tuple[int, int]]) -> List[int]:
action_map = {
"N": 0,
"E": 1,
"S": 2,
"W": 3,
"NE": 4,
"SE": 5,
"SW": 6,
"NW": 7
}
actions = []
x_s, y_s = start
for (x, y) in path:
if x_s == x:
if y_s > y:
actions.append(action_map["W"])
else: actions.append(action_map["E"])
elif y_s == y:
if x_s > x:
actions.append(action_map["N"])
else: actions.append(action_map["S"])
elif x_s > x and y_s < y:
actions.append(action_map["NE"])
elif x_s < x and y_s < y:
actions.append(action_map["SE"])
elif x_s < x and y_s > y:
actions.append(action_map["SW"])
elif x_s > x and y_s > y:
actions.append(action_map["NW"])
else:
raise Exception("Error")
x_s = x
y_s = y
return actions
def get_best_move(game_map: np.ndarray,
current_position: Tuple[int, int],
end_target: Tuple[int, int],
heuristic: Callable[[Tuple[int, int], Tuple[int, int]], int],
hp_percent: int,
weapon_in_hand: bool
) -> Tuple[int, int]:
moves = get_valid_moves(game_map,current_position)
min = float('inf')
coord = (0,0)
for move in moves: #scelgo quella che minimizza l'euristica
md = heuristic(game_map, move, end_target, hp_percent, weapon_in_hand)
if md < min:
min = md
coord = move
return coord
def plot_map(game_map: np.ndarray,image: AxesImage) -> np.ndarray:
display.display(plt.gcf())
#time.sleep(0.5)
display.clear_output(wait=True)
image.set_data(game_map['pixel'][:, 300:975])
#fine stampa
#aggiorno game_map
return game_map["chars"]
def euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def manhattan_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> int:
x1, y1 = point1
x2, y2 = point2
return abs(x1 - x2) + abs(y1 - y2)
def pickup():
env.step(8) # 8 = pickup the item
def wield(): # Tested and working
obs, _, _, _ = env.step(9) # 9 = wield
# Example message: What do you want to wield? [- abf or ?*]
message = bytes(obs['message']).decode('utf-8').rstrip('\x00')
#print("Message: ", message) # debug
# split -> ['What do you want to wield? ', '- abf or ?*']
# we get the second part (index 1), then we get the fourth char of the second part
# in this case "f" is the dagger (index 4)
weapon_char = message.split('[')[1][4]
#print("Weapon char: ", weapon_char) # debug
env.step(env.actions.index(ord(weapon_char))) # select weapon from inventory
# New message after wielding: f- a dagger (weapon in hand). Uncomment to see it.
#message = bytes(obs['message']).decode('utf-8').rstrip('\x00') #debug
#print("Message: ", message) # debug
def generate_map():
map_layout = """
--------------------
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
|..................|
--------------------
"""
lvl_gen = LevelGenerator(map = map_layout)
# starting position
lvl_gen.set_start_pos((5, 2))
# dagger position
#lvl_gen.add_object("spear", ")", (18,18))
lvl_gen.add_object("dagger", ")", (18,18))
# group of monster low right
lvl_gen.add_monster("kobold zombie", "Z", (21,18))
lvl_gen.add_monster("kobold zombie", "Z", (22,18))
# group of monster high right
lvl_gen.add_monster("kobold zombie", "Z", (22,1))
lvl_gen.add_monster("kobold zombie", "Z", (22,2))
# single monster low left
lvl_gen.add_monster("kobold zombie", "Z", (5,18))
lvl_gen.add_goal_pos((16,12))
return lvl_gen
# def generate_map():
# map_layout = """
# --------------------
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# |..................|
# --------------------
# """
# lvl_gen = LevelGenerator(map = map_layout)
# # starting position
# lvl_gen.set_start_pos((10, 10))
# # dagger position
# #lvl_gen.add_object("spear", ")", (15,15))
# lvl_gen.add_object("dagger", ")", (17,12))
# # group of monster low right
# lvl_gen.add_monster("kobold zombie", "Z", (8,9))
# lvl_gen.add_monster("kobold zombie", "Z", (2,10))
# # group of monster high right
# lvl_gen.add_monster("kobold zombie", "Z", (10,8))
# lvl_gen.add_monster("kobold zombie", "Z", (11,12))
# # single monster low left
# lvl_gen.add_monster("kobold zombie", "Z", (14,10))
# lvl_gen.add_goal_pos((16,12))
# return lvl_gen
def generate_env():
env = gym.make("MiniHack-Skill-Custom-v0",
observation_keys=("chars", "pixel", "blstats", "message"),
des_file = map.get_des(),
actions = OTHER_ACTIONS,
)
return env
def hp_plots(hp_history_1: np.array, moves_history_1: np.array, hp_history_2: np.array, moves_history_2: np.array, brave_threshold: int):
fig = plt.figure()
fig.suptitle('HP History', fontsize=12, fontweight='bold')
# Plot the HP history for the first set of data (curve 1)
plt.plot(moves_history_1, hp_history_1, label='Heuristic #1', color='blue')
# Plot the HP history for the second set of data (curve 2)
plt.plot(moves_history_2, hp_history_2, label='Heuristic #2', color='red')
# Set labels and title
plt.xlabel('Time')
plt.ylabel('HP')
plt.title('Brave threshold: ' + str(brave_threshold))
plt.axhline(y=brave_threshold, color='grey', linestyle='--', label='Brave threshold')
# Add legend
plt.legend()
# Show the plot
plt.show()
map = generate_map()
env = generate_env()