Repository navigation
Expand file tree
/
Copy pathenv.py
More file actions
378 lines (324 loc) · 12.3 KB
/
Copy pathenv.py
File metadata and controls
378 lines (324 loc) · 12.3 KB
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
"""Shadow Heist OpenEnv-compatible stealth environment."""
from __future__ import annotations
from dataclasses import dataclass
import random
from typing import Any, Dict, List, Optional, Sequence, Tuple
GridPos = Tuple[int, int]
ACTION_SPACE = (
"move_up",
"move_down",
"move_left",
"move_right",
"hide",
"steal",
"wait",
)
@dataclass
class GuardAgent:
"""State for an autonomous guard."""
position: GridPos
patrol_path: List[GridPos]
patrol_index: int = 0
alerted: bool = False
last_seen_player: Optional[GridPos] = None
class ShadowHeistEnv:
"""Grid-based stealth strategy environment with partial observability."""
def __init__(
self,
grid_size: int = 8,
num_guards: int = 2,
num_treasures: int = 3,
detection_radius: int = 2,
visibility_radius: int = 2,
max_detection_steps: int = 2,
hide_detection_multiplier: float = 0.35,
max_steps: int = 100,
seed: Optional[int] = None,
) -> None:
if grid_size < 5:
raise ValueError("grid_size must be at least 5.")
if num_guards < 1:
raise ValueError("num_guards must be at least 1.")
if num_treasures < 1:
raise ValueError("num_treasures must be at least 1.")
if max_detection_steps < 1:
raise ValueError("max_detection_steps must be at least 1.")
self.grid_size = grid_size
self.num_guards = num_guards
self.num_treasures = num_treasures
self.detection_radius = detection_radius
self.visibility_radius = visibility_radius
self.max_detection_steps = max_detection_steps
self.hide_detection_multiplier = hide_detection_multiplier
self.max_steps = max_steps
self._base_seed = seed
self._rng = random.Random(seed)
self.player_pos: GridPos = (0, 0)
self.exit_pos: GridPos = (0, 0)
self.treasures: List[GridPos] = []
self.guards: List[GuardAgent] = []
self.detected_steps = 0
self.collected_treasures = 0
self.hidden = False
self.done = False
self.caught = False
self.escaped = False
self.step_count = 0
self.last_action = "wait"
self.seen_cells: set[GridPos] = set()
def reset(self, seed: Optional[int] = None) -> Dict[str, Any]:
"""Start a fresh episode and return the initial state."""
if seed is not None:
self._rng = random.Random(seed)
elif self._base_seed is not None:
self._rng = random.Random(self._base_seed)
cells = [(x, y) for x in range(self.grid_size) for y in range(self.grid_size)]
self._rng.shuffle(cells)
required = 2 + self.num_treasures + self.num_guards
if required > len(cells):
raise ValueError("Configuration requests more entities than grid cells.")
self.player_pos = cells.pop()
self.exit_pos = self._pick_far_cell(cells, self.player_pos)
cells.remove(self.exit_pos)
self.treasures = []
for _ in range(self.num_treasures):
treasure = self._pick_far_cell(cells, self.exit_pos)
cells.remove(treasure)
self.treasures.append(treasure)
self.guards = []
for _ in range(self.num_guards):
guard_pos = self._pick_far_cell(cells, self.player_pos)
cells.remove(guard_pos)
self.guards.append(
GuardAgent(
position=guard_pos,
patrol_path=self._build_patrol_path(guard_pos, blocked={self.exit_pos}),
)
)
self.detected_steps = 0
self.collected_treasures = 0
self.hidden = False
self.done = False
self.caught = False
self.escaped = False
self.step_count = 0
self.last_action = "reset"
self.seen_cells = {self.player_pos}
return self.state()
def step(self, action: str) -> Tuple[Dict[str, Any], float, bool, Dict[str, Any]]:
"""Advance the environment by one action."""
if self.done:
raise RuntimeError("Episode has finished. Call reset() before step().")
if action not in ACTION_SPACE:
raise ValueError(f"Unknown action '{action}'. Valid actions: {', '.join(ACTION_SPACE)}")
self.step_count += 1
self.last_action = action
reward = 0.0
info: Dict[str, Any] = {
"action": action,
"treasure_stolen": False,
"detected": False,
"caught": False,
"escaped": False,
"invalid_move": False,
}
self.hidden = action == "hide"
moved = False
previous_pos = self.player_pos
if action.startswith("move_"):
moved = self._move_player(action)
if not moved:
reward -= 1.0
info["invalid_move"] = True
self.hidden = False
elif action == "steal":
if self.player_pos in self.treasures:
self.treasures.remove(self.player_pos)
self.collected_treasures += 1
reward += 10.0
info["treasure_stolen"] = True
else:
reward -= 0.5
self.hidden = False
elif action == "wait":
reward -= 0.1
self.hidden = False
elif action == "hide":
reward += 0.2
if self.player_pos not in self.seen_cells:
self.seen_cells.add(self.player_pos)
reward += 0.1
info["exploration_bonus"] = 0.1
else:
info["exploration_bonus"] = 0.0
self._move_guards()
detected = self._update_detection()
info["detected"] = detected
if moved and not detected:
reward += 1.0
if detected:
reward -= 5.0
elif self.detected_steps == 0 and self.player_pos != previous_pos:
reward += 0.1
if self.player_pos == self.exit_pos and self.collected_treasures > 0 and not self.caught:
self.done = True
self.escaped = True
reward += 100.0
info["escaped"] = True
if self.detected_steps >= self.max_detection_steps:
self.done = True
self.caught = True
reward -= 50.0
info["caught"] = True
if self.step_count >= self.max_steps and not self.done:
self.done = True
reward -= 10.0
info["truncated"] = True
else:
info["truncated"] = False
state = self.state()
info["state"] = state
return state, round(reward, 3), self.done, info
def state(self) -> Dict[str, Any]:
"""Return the current partially observable environment state."""
return {
"player_pos": self.player_pos,
"guards": [guard.position for guard in self.guards],
"treasures": list(self.treasures),
"exit": self.exit_pos,
"visible_grid": self._build_visible_grid(),
"collected_treasures": self.collected_treasures,
"remaining_treasures": len(self.treasures),
"detected_steps": self.detected_steps,
"hidden": self.hidden,
"step_count": self.step_count,
"done": self.done,
"caught": self.caught,
"escaped": self.escaped,
"available_actions": list(ACTION_SPACE),
}
def render(self) -> str:
"""Return an ASCII rendering of the visible grid."""
return "\n".join(" ".join(row) for row in self._build_visible_grid())
def _move_player(self, action: str) -> bool:
dx, dy = {
"move_up": (0, -1),
"move_down": (0, 1),
"move_left": (-1, 0),
"move_right": (1, 0),
}[action]
next_pos = (self.player_pos[0] + dx, self.player_pos[1] + dy)
if not self._in_bounds(next_pos):
return False
self.player_pos = next_pos
return True
def _move_guards(self) -> None:
occupied = {guard.position for guard in self.guards}
for guard in self.guards:
occupied.discard(guard.position)
currently_detects = self._guard_detects(guard)
if currently_detects:
guard.alerted = True
guard.last_seen_player = self.player_pos
elif guard.alerted and guard.position == guard.last_seen_player:
guard.alerted = False
guard.last_seen_player = None
if guard.alerted and guard.last_seen_player:
next_pos = self._step_toward(guard.position, guard.last_seen_player, occupied)
else:
guard.patrol_index = (guard.patrol_index + 1) % len(guard.patrol_path)
next_pos = guard.patrol_path[guard.patrol_index]
if next_pos in occupied:
next_pos = guard.position
guard.position = next_pos
occupied.add(guard.position)
def _update_detection(self) -> bool:
if not self.treasures:
self.detected_steps = max(0, self.detected_steps - 1)
return False
detected = any(self._guard_detects(guard) for guard in self.guards)
if detected:
self.detected_steps += 1
else:
self.detected_steps = max(0, self.detected_steps - 1)
return detected
def _guard_detects(self, guard: GuardAgent) -> bool:
distance = self._manhattan_distance(guard.position, self.player_pos)
if distance > self.detection_radius:
return False
chance = max(0.25, 1.0 - (0.15 * distance))
if self.hidden:
chance *= self.hide_detection_multiplier
return self._rng.random() < chance
def _build_visible_grid(self) -> List[List[str]]:
grid = [["?" for _ in range(self.grid_size)] for _ in range(self.grid_size)]
px, py = self.player_pos
visible_guards = {guard.position for guard in self.guards}
visible_treasures = set(self.treasures)
for y in range(self.grid_size):
for x in range(self.grid_size):
if abs(px - x) + abs(py - y) > self.visibility_radius:
continue
cell = "."
pos = (x, y)
if pos == self.exit_pos:
cell = "E"
if pos in visible_treasures:
cell = "T"
if pos in visible_guards:
cell = "G"
if pos == self.player_pos:
cell = "P"
grid[y][x] = cell
return grid
def _build_patrol_path(
self,
anchor: GridPos,
blocked: Optional[set[GridPos]] = None,
) -> List[GridPos]:
blocked = blocked or set()
candidates = [
anchor,
(anchor[0] + 1, anchor[1]),
(anchor[0], anchor[1] + 1),
(anchor[0] - 1, anchor[1]),
(anchor[0], anchor[1] - 1),
]
path: List[GridPos] = []
for pos in candidates:
if self._in_bounds(pos) and pos not in path and pos not in blocked:
path.append(pos)
return path or [anchor]
def _pick_far_cell(self, cells: Sequence[GridPos], reference: GridPos) -> GridPos:
ranked = sorted(
cells,
key=lambda cell: (self._manhattan_distance(cell, reference), self._rng.random()),
reverse=True,
)
return ranked[0]
def _step_toward(
self,
start: GridPos,
goal: GridPos,
occupied: set[GridPos],
) -> GridPos:
x, y = start
gx, gy = goal
candidates = []
if gx > x:
candidates.append((x + 1, y))
elif gx < x:
candidates.append((x - 1, y))
if gy > y:
candidates.append((x, y + 1))
elif gy < y:
candidates.append((x, y - 1))
for candidate in candidates:
if self._in_bounds(candidate) and candidate not in occupied:
return candidate
return start
def _in_bounds(self, pos: GridPos) -> bool:
return 0 <= pos[0] < self.grid_size and 0 <= pos[1] < self.grid_size
@staticmethod
def _manhattan_distance(a: GridPos, b: GridPos) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])