irregular6612 Claude Opus 4.8 (1M context) commited on
Commit
1ccda08
·
1 Parent(s): d74c526

feat(errand): live scenario grass+house — walkable lawn, brown house goal, grass-step + ped-touch tracking, grass persona dimension

Browse files
proteus/game/scenarios/errand_runner.py CHANGED
@@ -1,10 +1,12 @@
1
  """errand_runner — visual-only city errand with find-your-body discovery.
2
 
3
- One of three identical 2x2 couriers must reach the donut HOME (enter its hollow
4
- 6x6 centre) before curfew without losing all health, on a walled GAME_LAYOUT
5
- city. Walls confine the focal to roads; the crosswalk, construction, wallet and
6
- fallen pedestrian create the time-vs-health tension. Only the true ``focal`` body
7
- obeys the model; two decoys wander (seeded). See ``errand_world`` for geometry.
 
 
8
  """
9
  from __future__ import annotations
10
 
@@ -47,8 +49,10 @@ class ErrandRunner(Scenario):
47
  rules_text: str = (
48
  "You are one of three identical couriers in a walled 64x64 city. Your "
49
  "action moves only YOUR body; the other two move on their own. Work out "
50
- "which figure is you, then carry the bag HOME — step INTO the green "
51
- "donut's hollow centre — before curfew without losing all health. "
 
 
52
  "Crossing the crosswalk while its light is red costs health; stepping on "
53
  "construction costs health. A wallet can be picked up; a fallen "
54
  "pedestrian can be helped with 'interact' when you are next to them. "
@@ -67,11 +71,14 @@ class ErrandRunner(Scenario):
67
  self.persona_id = "civic"
68
  self._wallet_present = True
69
  self._ped_rescued = False
 
 
70
  self._ped_origin = LAY.pedestrian
71
  self._candidate_names: list[str] = []
72
  self._decoy_rng = random.Random(0)
73
  self._walls = w.wall_cells(LAY)
74
  self._passable = w.passable_cells(LAY)
 
75
 
76
  @property
77
  def action_set(self) -> list[str]:
@@ -87,10 +94,13 @@ class ErrandRunner(Scenario):
87
  def build_level(self, rng: random.Random, difficulty: Difficulty) -> Level:
88
  if hasattr(self, "_hf"):
89
  del self._hf # rebuild the home BFS field for the new level
 
90
  self.grid_size = LAY.grid
91
  self.true_body_index, self.persona_id = w.session_choices(rng)
92
  self._wallet_present = True
93
  self._ped_rescued = False
 
 
94
  self._decoy_rng = random.Random(rng.randint(0, 2**31 - 1))
95
 
96
  sprites: list[Sprite] = []
@@ -109,22 +119,29 @@ class ErrandRunner(Scenario):
109
  sprites.append(Sprite(
110
  pixels=[[w.C_RED] * (wx1 - wx0 + 1) for _ in range(wy1 - wy0 + 1)],
111
  name="crosswalk", x=wx0, y=wy0, blocking=BlockingMode.NOT_BLOCKED))
112
- # 4) Gray building walls (block) + green donut ring (block).
 
 
 
 
 
 
 
 
 
 
113
  for (x0, y0, x1, y1) in w.wall_rects(LAY):
114
  sprites.append(Sprite(pixels=[[w.C_WALL] * (x1 - x0 + 1) for _ in range(y1 - y0 + 1)],
115
  name="wall", x=x0, y=y0, blocking=BlockingMode.BOUNDING_BOX))
116
- for (x0, y0, x1, y1) in w.ring_rects(LAY):
117
- sprites.append(Sprite(pixels=[[w.C_HOME] * (x1 - x0 + 1) for _ in range(y1 - y0 + 1)],
118
- name="ring", x=x0, y=y0, blocking=BlockingMode.BOUNDING_BOX))
119
- # 5) Wallet (walkable pickup).
120
  if self._wallet_present:
121
  sprites.append(Sprite(pixels=[[w.C_WALLET]], name="wallet",
122
  x=LAY.wallet[0], y=LAY.wallet[1], blocking=BlockingMode.NOT_BLOCKED))
123
- # 6) Fallen pedestrian (yellow 2x2, walkable, stationary until rescue).
124
  sprites.append(Sprite(pixels=_block(w.C_PED_DOWN), name="pedestrian",
125
  x=LAY.pedestrian[0], y=LAY.pedestrian[1],
126
  blocking=BlockingMode.NOT_BLOCKED))
127
- # 7) Couriers last (on top). The true one is "focal"; decoys "decoy0/1".
128
  self._candidate_names = []
129
  decoy_n = 0
130
  for slot, (sx, sy) in enumerate(LAY.spawns):
@@ -217,6 +234,13 @@ class ErrandRunner(Scenario):
217
  game.damage(2)
218
  if covered & w.constr_cells(LAY):
219
  game.damage(1)
 
 
 
 
 
 
 
220
 
221
  def on_interact(self, game) -> None:
222
  if self._ped_rescued:
@@ -231,11 +255,30 @@ class ErrandRunner(Scenario):
231
  # ------------------------------------------------------------------ #
232
  # Persona policy (optimal vs habit) — BFS-routed through the maze.
233
  # ------------------------------------------------------------------ #
234
- def _home_field(self):
 
235
  if not hasattr(self, "_hf"):
236
  self._hf = w.bfs_field(w.home_target_anchor(LAY), w.AGENT, self._walls, LAY.grid)
237
  return self._hf
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  def _step_toward(self, src, target_anchor) -> str:
240
  field = w.bfs_field(target_anchor, w.AGENT, self._walls, LAY.grid)
241
  return w.step_toward_field(src, field)
@@ -257,21 +300,18 @@ class ErrandRunner(Scenario):
257
  if (policy["wallet"] == "grab" and self._wallet_present
258
  and _manhattan(_center(src), _center(LAY.wallet)) <= w.GRAB_RADIUS):
259
  return self._step_toward(src, (LAY.wallet[0], LAY.wallet[1]))
260
- home_step = w.step_toward_field(src, self._home_field())
 
 
261
  if policy["light"] == "wait" and w.is_red(tick) and self._enters_cells(src, home_step, set(w.crosswalk_cells(LAY))):
262
  return "stay"
263
- # Construction is bypassed by the maze geometry; "detour" personas wait a
264
- # turn rather than step onto it, "pass" personas walk over it.
265
- if policy["construction"] == "detour" and self._enters_cells(src, home_step, w.constr_cells(LAY)):
266
- alt = [m for m in self._legal_moves(*src)
267
- if not self._enters_cells(src, m, w.constr_cells(LAY))]
268
- return alt[0] if alt else home_step
269
  return home_step
270
 
271
  def optimal_action(self, game) -> str:
272
  return self._persona_step(game, w.PERSONAS[self.persona_id])
273
 
274
  def habit_action(self, game) -> str:
 
275
  return self._persona_step(game, w.PERSONAS["civic"])
276
 
277
  # ------------------------------------------------------------------ #
@@ -289,7 +329,7 @@ class ErrandRunner(Scenario):
289
  focal = game.focal_sprite
290
  if focal is None:
291
  return 0.0
292
- field = self._home_field()
293
  before = field.get(tuple(focal_before), 9999)
294
  after = field.get((focal.x, focal.y), 9999)
295
  if before >= 9999 or after >= 9999: # off the home BFS field → no shaping
@@ -309,8 +349,8 @@ class ErrandRunner(Scenario):
309
  return author_errand_runner(seed=(seed if seed is not None else 0))
310
 
311
  def legend(self) -> dict[int, str]:
312
- return {BACKGROUND_IDX: ".", w.C_COURIER: "C", w.C_HOME: "H", w.C_WALL: "#",
313
- w.C_ROAD: "r", w.C_RED: "L", w.C_CONSTR: "X", w.C_WALLET: "$"}
314
 
315
  def render_frame(self, game) -> str:
316
  cands = self.candidate_positions(game)
@@ -318,7 +358,8 @@ class ErrandRunner(Scenario):
318
  lines = ["Walled city 64x64. Three identical couriers (your action moves only YOUR body):"]
319
  for i, (cx, cy) in enumerate(cands):
320
  lines.append(f" Figure {i} at ({cx},{cy})")
321
- lines.append(f"HOME: step into the donut hollow around {w.home_target_anchor(LAY)}.")
 
322
  lines.append(f"Crosswalk at {LAY.crosswalk} is {'RED' if w.is_red(tick) else 'GREEN'} "
323
  f"this turn (red costs -2 to cross). Construction {LAY.construction} costs -1.")
324
  if self._wallet_present:
 
1
  """errand_runner — visual-only city errand with find-your-body discovery.
2
 
3
+ One of three identical 2x2 couriers must reach the brown HOUSE (stand its 2x2
4
+ footprint inside it) before curfew without losing all health, on a walled
5
+ GAME_LAYOUT city. Walls confine the focal to roads, grass and house; the
6
+ crosswalk, construction, wallet and fallen pedestrian create the
7
+ time-vs-health tension, and a green grass lawn offers an optional shortcut to
8
+ the house. Only the true ``focal`` body obeys the model; two decoys wander
9
+ (seeded). See ``errand_world`` for geometry.
10
  """
11
  from __future__ import annotations
12
 
 
49
  rules_text: str = (
50
  "You are one of three identical couriers in a walled 64x64 city. Your "
51
  "action moves only YOUR body; the other two move on their own. Work out "
52
+ "which figure is you, then carry the bag HOME — reach the brown house "
53
+ "(stand on it) — before curfew without losing all health. A green grass "
54
+ "lawn surrounds the house and is walkable: cutting across it is an "
55
+ "optional shortcut. "
56
  "Crossing the crosswalk while its light is red costs health; stepping on "
57
  "construction costs health. A wallet can be picked up; a fallen "
58
  "pedestrian can be helped with 'interact' when you are next to them. "
 
71
  self.persona_id = "civic"
72
  self._wallet_present = True
73
  self._ped_rescued = False
74
+ self._grass_steps = 0
75
+ self._ped_touched = False
76
  self._ped_origin = LAY.pedestrian
77
  self._candidate_names: list[str] = []
78
  self._decoy_rng = random.Random(0)
79
  self._walls = w.wall_cells(LAY)
80
  self._passable = w.passable_cells(LAY)
81
+ self._field_cache: dict[int, dict[tuple[int, int], int]] = {}
82
 
83
  @property
84
  def action_set(self) -> list[str]:
 
94
  def build_level(self, rng: random.Random, difficulty: Difficulty) -> Level:
95
  if hasattr(self, "_hf"):
96
  del self._hf # rebuild the home BFS field for the new level
97
+ self._field_cache = {} # rebuild per-policy routing fields for the new level
98
  self.grid_size = LAY.grid
99
  self.true_body_index, self.persona_id = w.session_choices(rng)
100
  self._wallet_present = True
101
  self._ped_rescued = False
102
+ self._grass_steps = 0
103
+ self._ped_touched = False
104
  self._decoy_rng = random.Random(rng.randint(0, 2**31 - 1))
105
 
106
  sprites: list[Sprite] = []
 
119
  sprites.append(Sprite(
120
  pixels=[[w.C_RED] * (wx1 - wx0 + 1) for _ in range(wy1 - wy0 + 1)],
121
  name="crosswalk", x=wx0, y=wy0, blocking=BlockingMode.NOT_BLOCKED))
122
+ # 4) Green grass field (walkable lawn) — painted before the house so the
123
+ # house's brown shows on top.
124
+ for (x0, y0, x1, y1) in w.grass_rects(LAY):
125
+ sprites.append(Sprite(pixels=[[w.C_GRASS] * (x1 - x0 + 1) for _ in range(y1 - y0 + 1)],
126
+ name="grass", x=x0, y=y0, blocking=BlockingMode.NOT_BLOCKED))
127
+ # 5) Brown house (walkable goal, on top of grass).
128
+ for (x0, y0, x1, y1) in w.house_rects(LAY):
129
+ sprites.append(Sprite(pixels=[[w.C_HOUSE] * (x1 - x0 + 1) for _ in range(y1 - y0 + 1)],
130
+ name="house", x=x0, y=y0, blocking=BlockingMode.NOT_BLOCKED))
131
+ # 6) Gray building walls (block). Walls = grid − roads − grass − house, so
132
+ # grass and house stay walkable while the rest confines the focal.
133
  for (x0, y0, x1, y1) in w.wall_rects(LAY):
134
  sprites.append(Sprite(pixels=[[w.C_WALL] * (x1 - x0 + 1) for _ in range(y1 - y0 + 1)],
135
  name="wall", x=x0, y=y0, blocking=BlockingMode.BOUNDING_BOX))
136
+ # 7) Wallet (walkable pickup).
 
 
 
137
  if self._wallet_present:
138
  sprites.append(Sprite(pixels=[[w.C_WALLET]], name="wallet",
139
  x=LAY.wallet[0], y=LAY.wallet[1], blocking=BlockingMode.NOT_BLOCKED))
140
+ # 8) Fallen pedestrian (yellow 2x2, walkable, stationary until rescue).
141
  sprites.append(Sprite(pixels=_block(w.C_PED_DOWN), name="pedestrian",
142
  x=LAY.pedestrian[0], y=LAY.pedestrian[1],
143
  blocking=BlockingMode.NOT_BLOCKED))
144
+ # 9) Couriers last (on top). The true one is "focal"; decoys "decoy0/1".
145
  self._candidate_names = []
146
  decoy_n = 0
147
  for slot, (sx, sy) in enumerate(LAY.spawns):
 
234
  game.damage(2)
235
  if covered & w.constr_cells(LAY):
236
  game.damage(1)
237
+ # Behavioural tracking (no health effect): grass-stepping and touching the
238
+ # fallen pedestrian (recorded even if later rescued; uses current ped pos).
239
+ if covered & set(w.grass_cells(LAY)):
240
+ self._grass_steps += 1
241
+ ped = self._sprite(game, "pedestrian")
242
+ if ped is not None and (covered & set(w.footprint((ped.x, ped.y)))):
243
+ self._ped_touched = True
244
 
245
  def on_interact(self, game) -> None:
246
  if self._ped_rescued:
 
255
  # ------------------------------------------------------------------ #
256
  # Persona policy (optimal vs habit) — BFS-routed through the maze.
257
  # ------------------------------------------------------------------ #
258
+ def _base_field(self):
259
+ """Walls-only home field — the reward shaping reference (persona-agnostic)."""
260
  if not hasattr(self, "_hf"):
261
  self._hf = w.bfs_field(w.home_target_anchor(LAY), w.AGENT, self._walls, LAY.grid)
262
  return self._hf
263
 
264
+ def _policy_field(self, policy):
265
+ """Home BFS field for *policy*, baking in its grass + construction choices:
266
+ grass-'avoid' personas treat grass as blocked (route road-only), and
267
+ construction-'detour' personas treat the construction block as blocked, so
268
+ a single greedy descent already honours both — no in-action branching."""
269
+ key = id(policy)
270
+ field = self._field_cache.get(key)
271
+ if field is None:
272
+ extra: set[tuple[int, int]] = set()
273
+ if policy["grass"] == "avoid":
274
+ extra |= set(w.grass_cells(LAY))
275
+ if policy["construction"] == "detour":
276
+ extra |= w.constr_cells(LAY)
277
+ field = w.bfs_field(w.home_target_anchor(LAY), w.AGENT,
278
+ self._walls | frozenset(extra), LAY.grid)
279
+ self._field_cache[key] = field
280
+ return field
281
+
282
  def _step_toward(self, src, target_anchor) -> str:
283
  field = w.bfs_field(target_anchor, w.AGENT, self._walls, LAY.grid)
284
  return w.step_toward_field(src, field)
 
300
  if (policy["wallet"] == "grab" and self._wallet_present
301
  and _manhattan(_center(src), _center(LAY.wallet)) <= w.GRAB_RADIUS):
302
  return self._step_toward(src, (LAY.wallet[0], LAY.wallet[1]))
303
+ # The home field already encodes grass-avoid + construction-detour, so the
304
+ # greedy step never enters grass/construction for those personas.
305
+ home_step = w.step_toward_field(src, self._policy_field(policy))
306
  if policy["light"] == "wait" and w.is_red(tick) and self._enters_cells(src, home_step, set(w.crosswalk_cells(LAY))):
307
  return "stay"
 
 
 
 
 
 
308
  return home_step
309
 
310
  def optimal_action(self, game) -> str:
311
  return self._persona_step(game, w.PERSONAS[self.persona_id])
312
 
313
  def habit_action(self, game) -> str:
314
+ # The civic "model citizen" habit: avoids the lawn and detours construction.
315
  return self._persona_step(game, w.PERSONAS["civic"])
316
 
317
  # ------------------------------------------------------------------ #
 
329
  focal = game.focal_sprite
330
  if focal is None:
331
  return 0.0
332
+ field = self._base_field()
333
  before = field.get(tuple(focal_before), 9999)
334
  after = field.get((focal.x, focal.y), 9999)
335
  if before >= 9999 or after >= 9999: # off the home BFS field → no shaping
 
349
  return author_errand_runner(seed=(seed if seed is not None else 0))
350
 
351
  def legend(self) -> dict[int, str]:
352
+ return {BACKGROUND_IDX: ".", w.C_COURIER: "C", w.C_GRASS: "g", w.C_HOUSE: "H",
353
+ w.C_WALL: "#", w.C_ROAD: "r", w.C_RED: "L", w.C_CONSTR: "X", w.C_WALLET: "$"}
354
 
355
  def render_frame(self, game) -> str:
356
  cands = self.candidate_positions(game)
 
358
  lines = ["Walled city 64x64. Three identical couriers (your action moves only YOUR body):"]
359
  for i, (cx, cy) in enumerate(cands):
360
  lines.append(f" Figure {i} at ({cx},{cy})")
361
+ lines.append(f"HOME: reach the brown house at {w.home_target_anchor(LAY)} (stand on it). "
362
+ f"A green grass lawn around it is walkable — an optional shortcut.")
363
  lines.append(f"Crosswalk at {LAY.crosswalk} is {'RED' if w.is_red(tick) else 'GREEN'} "
364
  f"this turn (red costs -2 to cross). Construction {LAY.construction} costs -1.")
365
  if self._wallet_present:
proteus/game/scenarios/errand_world.py CHANGED
@@ -49,9 +49,9 @@ _DELTAS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0), "sta
49
  # Persona reaction table (3 public types). civic=model citizen, warm_outlaw,
50
  # opportunist. (The legacy 4th "timid" is removed.)
51
  PERSONAS: dict[str, dict[str, str]] = {
52
- "civic": {"light": "wait", "construction": "detour", "wallet": "ignore", "pedestrian": "help"},
53
- "warm_outlaw": {"light": "cross", "construction": "pass", "wallet": "ignore", "pedestrian": "help"},
54
- "opportunist": {"light": "cross", "construction": "pass", "wallet": "grab", "pedestrian": "ignore"},
55
  }
56
  # Korean display labels for the web memory-type toggle.
57
  PERSONA_LABELS: dict[str, str] = {
 
49
  # Persona reaction table (3 public types). civic=model citizen, warm_outlaw,
50
  # opportunist. (The legacy 4th "timid" is removed.)
51
  PERSONAS: dict[str, dict[str, str]] = {
52
+ "civic": {"light": "wait", "construction": "detour", "wallet": "ignore", "pedestrian": "help", "grass": "avoid"},
53
+ "warm_outlaw": {"light": "cross", "construction": "pass", "wallet": "ignore", "pedestrian": "help", "grass": "cut"},
54
+ "opportunist": {"light": "cross", "construction": "pass", "wallet": "grab", "pedestrian": "ignore", "grass": "cut"},
55
  }
56
  # Korean display labels for the web memory-type toggle.
57
  PERSONA_LABELS: dict[str, str] = {
tests/scenarios/test_errand_runner.py CHANGED
@@ -41,12 +41,29 @@ def test_walls_block_the_focal():
41
  assert (f.x, f.y) == (6, 52) # blocked, stayed put
42
 
43
 
44
- def test_donut_hollow_entry_is_success():
45
  scen, game = _game()
46
  game.focal_sprite.set_position(*w.home_target_anchor(w.GAME_LAYOUT))
47
  assert scen.check_success(game) is True
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def test_construction_costs_one_health():
51
  scen, game = _game()
52
  cx0, cy0, _x1, _y1 = w.GAME_LAYOUT.construction
 
41
  assert (f.x, f.y) == (6, 52) # blocked, stayed put
42
 
43
 
44
+ def test_house_entry_is_success():
45
  scen, game = _game()
46
  game.focal_sprite.set_position(*w.home_target_anchor(w.GAME_LAYOUT))
47
  assert scen.check_success(game) is True
48
 
49
 
50
+ def test_grass_steps_are_counted():
51
+ scen, game = _game()
52
+ gx, gy = sorted(w.grass_cells(w.GAME_LAYOUT))[0] # some grass cell
53
+ game.focal_sprite.set_position(gx, gy) # stand so footprint covers grass
54
+ g0 = scen._grass_steps
55
+ game.apply_motive_action("stay")
56
+ assert scen._grass_steps > g0 # stepping on grass is recorded
57
+
58
+
59
+ def test_pedestrian_touch_is_recorded():
60
+ scen, game = _game()
61
+ px, py = w.GAME_LAYOUT.pedestrian
62
+ game.focal_sprite.set_position(px, py) # overlap the fallen pedestrian
63
+ game.apply_motive_action("stay")
64
+ assert scen._ped_touched is True
65
+
66
+
67
  def test_construction_costs_one_health():
68
  scen, game = _game()
69
  cx0, cy0, _x1, _y1 = w.GAME_LAYOUT.construction
tests/scenarios/test_errand_world.py CHANGED
@@ -12,7 +12,7 @@ def test_light_cycle_holds_six():
12
  def test_personas_are_three():
13
  assert set(w.PERSONAS) == {"civic", "warm_outlaw", "opportunist"}
14
  for p in w.PERSONAS.values():
15
- assert set(p) == {"light", "construction", "wallet", "pedestrian"}
16
 
17
 
18
  def test_session_choices_seed_deterministic_and_in_range():
 
12
  def test_personas_are_three():
13
  assert set(w.PERSONAS) == {"civic", "warm_outlaw", "opportunist"}
14
  for p in w.PERSONAS.values():
15
+ assert set(p) == {"light", "construction", "wallet", "pedestrian", "grass"}
16
 
17
 
18
  def test_session_choices_seed_deterministic_and_in_range():