Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions src/pokesim/cli/route_revisits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
r"""Grade AutoStory walks from a SerialPrograms log: the tiles each walked again.

PYTHONPATH=src python3 -m pokesim.cli.route_revisits SerialPrograms.log [--after "Lab: running r5"]

A route that crosses a tile twice walks back over its own way, which is
usually a planner or recovery choice worth a look. For each walk (a story
event's route, from its first leg to its last) it prints the legs, the
re-plans, the tiles walked against the tiles first planned, and the tiles
walked onto again.

It reads the walker's [Leg] lines (each leg's direction, tile count and end
tile) and its "[Route] <event>: plan from ..." lines. A leg is laid back
from its end along its direction. A leg that ended at an unknown tile places
nothing, and the next leg is laid back from its own end. A warp or a map
connection counts the tiles on the map left, short of the warp, and the end.
"""

import argparse
import json
import re
import sys

LEG = re.compile(r'\[Leg\] (\{.*\})\s*$')
PLAN = re.compile(r'\[Route\] (.+?): plan from (.+?): (.*)$')
PLACE = re.compile(r'^(\S+) \((\d+), (\d+)\)$')
PLANNED_LEG = re.compile(r'\b(north|south|east|west) (\d+)\b')
STEP = {'north': (0, -1), 'south': (0, 1), 'east': (1, 0), 'west': (-1, 0)}


class Grade:
"""One walk: a story event's legs from its first on."""

def __init__(self, checkpoint, event):
self.checkpoint, self.event = checkpoint, event
self.legs = 0
self.replans = 0
self.planned_tiles = 0
self.walked_tiles = 0
self.revisited = []
self.plans = 0
self.at = None
self.visited = set()

def plan(self, start, legs):
if self.plans == 0:
self.planned_tiles = sum(int(tiles) for _, tiles in PLANNED_LEG.findall(legs))
place = PLACE.match(start)
if place and self.at is None:
self.at = (place.group(1), int(place.group(2)), int(place.group(3)))
self.visited.add(self.at)
else:
self.replans += 1
self.plans += 1

def visit(self, tile):
if tile in self.visited:
self.revisited.append(tile)
else:
self.visited.add(tile)

def leg(self, record):
self.legs += 1
tiles = int(record.get('tiles', 0))
self.walked_tiles += tiles
end = record.get('end') or []
if not end:
self.at = None
return
end = (end[0][0], int(end[0][1]), int(end[0][2]))
dx, dy = STEP.get(record.get('dir'), (0, 0))
if tiles == 0 or end == self.at:
self.at = end
return
if self.at is not None and self.at[0] != end[0]:
# A warp or a connection: the map left, short of the warp, then the end.
for c in range(1, tiles):
self.visit((self.at[0], self.at[1] + dx * c, self.at[2] + dy * c))
self.visit(end)
else:
# Laid back from the end; where it starts, a leg that ended short
# of a known start doesn't say.
line = [(end[0], end[1] - dx * c, end[2] - dy * c) for c in range(tiles)]
if self.at is not None and self.at in line:
line = line[:line.index(self.at)]
for tile in reversed(line):
self.visit(tile)
self.at = end


def grade(lines):
"""[Grade] per walk in `lines`, in log order."""
grades = []
pending = []
for line in lines:
plan = PLAN.search(line)
if plan:
pending.append(plan.groups())
continue
found = LEG.search(line)
if not found:
continue
try:
record = json.loads(found.group(1))
except ValueError:
continue
current = grades[-1] if grades else None
key = (record.get('checkpoint'), record.get('event'))
if current is None or int(record.get('leg', 0)) == 1 or (current.checkpoint, current.event) != key:
current = Grade(*key)
grades.append(current)
for event, start, legs in pending:
if event == current.event:
current.plan(start, legs)
pending = []
current.leg(record)
return grades


def place_text(tile):
return '{} ({}, {})'.format(*tile)


def report(grades):
for g in grades:
revisited = '{} revisited'.format(len(g.revisited))
if g.revisited:
revisited += ': ' + ', '.join(place_text(tile) for tile in g.revisited)
print('{} {}: {} legs, {} re-plan{}, walked {} of {} planned tiles, {}'.format(
g.checkpoint, g.event, g.legs, g.replans, '' if g.replans == 1 else 's',
g.walked_tiles, g.planned_tiles, revisited))


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('log')
parser.add_argument('--after', help='read the log from the last line containing this text on')
args = parser.parse_args(argv)
with open(args.log, encoding='utf-8', errors='replace') as file:
lines = file.readlines()
if args.after:
starts = [c for c, line in enumerate(lines) if args.after in line]
if not starts:
print('No line contains: ' + args.after, file=sys.stderr)
return 1
lines = lines[starts[-1]:]
report(grade(lines))
return 0


if __name__ == '__main__':
sys.exit(main())
82 changes: 82 additions & 0 deletions src/pokesim/cli/test_route_revisits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Grades of AutoStory walks read from a SerialPrograms log's [Leg] lines."""

import io
import unittest
from contextlib import redirect_stdout

from pokesim.cli import route_revisits

PREFIX = '2026-11-15 15:04:35.057665 - [Console 0]: '


def leg(number, direction, tiles, end, planned_end=None, known='dead_reckoned', event='below_center_door'):
def place(at):
return '[]' if at is None else '[["{}",{},{}]]'.format(*at)
return PREFIX + ('[Leg] {{"checkpoint":"16.06","dir":"{}","end":{},"event":"{}","known":"{}","leg":{},'
'"planned_end":{},"tiles":{}}}').format(
direction, place(end), event, known, number, place(planned_end or end), tiles)


def plan(start, legs, event='below_center_door'):
return PREFIX + '[Route] {}: plan from {}: {}'.format(event, start, legs)


# 16.06 on console B (2026-11-15 15:04, r5), cut down: a position check after
# "west 4 (open)" on SilphCo_7F re-plans from an unknown tile, and the walk
# goes back east onto (1, 9), off the wall it was held to, and north onto
# (1, 7), where the leg checked had ended.
SILPH_7F = [
plan('SilphCo_7F (5, 8)', 'north 1 (to wall) to SilphCo_7F (5, 7); west 4 (open) to SilphCo_7F (1, 7); '
'north 3 (to wall) to SilphCo_7F (1, 4)'),
leg(1, 'north', 1, ('SilphCo_7F', 5, 7)),
leg(2, 'west', 4, ('SilphCo_7F', 1, 7)),
plan('an unknown tile', 'south 2 (to wall) to SilphCo_7F (3, 9); west 3 (to wall) to SilphCo_7F (0, 9); '
'east 1 (open) to SilphCo_7F (1, 9); north 2 (open) to SilphCo_7F (1, 7); north 3 (to wall) to SilphCo_7F (1, 4)'),
leg(3, 'south', 2, None, planned_end=('SilphCo_7F', 3, 9), known='unknown'),
leg(4, 'west', 3, ('SilphCo_7F', 0, 9)),
leg(5, 'east', 1, ('SilphCo_7F', 1, 9)),
leg(6, 'north', 2, ('SilphCo_7F', 1, 7)),
leg(7, 'north', 3, ('SilphCo_7F', 1, 4)),
]


class RouteRevisitsTest(unittest.TestCase):
def test_replan_walks_back_over_its_tiles(self):
grades = route_revisits.grade(SILPH_7F)
self.assertEqual(len(grades), 1)
grade = grades[0]
self.assertEqual((grade.checkpoint, grade.event), ('16.06', 'below_center_door'))
self.assertEqual(grade.legs, 7)
self.assertEqual(grade.replans, 1)
self.assertEqual(grade.planned_tiles, 8)
self.assertEqual(grade.walked_tiles, 16)
self.assertEqual(grade.revisited, [('SilphCo_7F', 1, 9), ('SilphCo_7F', 1, 7)])

def test_planned_walk_crosses_no_tile_twice(self):
grade = route_revisits.grade(SILPH_7F[:3] + SILPH_7F[-1:])[0]
self.assertEqual((grade.replans, grade.walked_tiles, grade.revisited), (0, 8, []))

def test_warp_starts_the_next_map(self):
lines = [
plan('SilphCo_11F (2, 19)', 'north 14 (warp) to SilphCo_7F (5, 8); north 1 (to wall) to SilphCo_7F (5, 7)'),
leg(1, 'north', 14, ('SilphCo_7F', 5, 8), known='fade'),
leg(2, 'north', 1, ('SilphCo_7F', 5, 7)),
]
grade = route_revisits.grade(lines)[0]
self.assertEqual((grade.planned_tiles, grade.walked_tiles, grade.revisited), (15, 15, []))

def test_a_new_first_leg_starts_another_walk(self):
lines = SILPH_7F[:3] + [leg(1, 'north', 1, ('SilphCo_7F', 5, 7))]
self.assertEqual([grade.legs for grade in route_revisits.grade(lines)], [2, 1])

def test_report(self):
out = io.StringIO()
with redirect_stdout(out):
route_revisits.report(route_revisits.grade(SILPH_7F))
self.assertEqual(out.getvalue().splitlines(), [
'16.06 below_center_door: 7 legs, 1 re-plan, walked 16 of 8 planned tiles, 2 revisited: SilphCo_7F (1, 9), SilphCo_7F (1, 7)',
])


if __name__ == '__main__':
unittest.main()
Loading