Coverage for src/retrospeedlab/search/environment/wrapper.py: 100%
41 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
1from typing import Any, ClassVar, Generic, TypeVar
3import numpy as np
4from numpy.typing import NDArray
6from retrospeedlab.engine.console import Console
7from retrospeedlab.search.environment.levels import Levels, level_map
8from retrospeedlab.search.ram import RamInfo
9from retrospeedlab.search.route.route_map import RouteMap
10from retrospeedlab.search.states.machine import StateMachine
11from retrospeedlab.search.states.state import State
13T = TypeVar("T", bound=RamInfo, covariant=True)
15ACTION_TABLE_DIMENSIONS = 3
18def state_class(state_classes: tuple[type[State[T]], ...], state_name: str) -> type[State[T]]:
19 for state_cls in state_classes:
20 if state_cls.__name__ == state_name:
21 return state_cls
22 raise ValueError(f"Unknown state: {state_name}")
25def phases(wrapper_cls: type["StateMachineGymWrapper[RamInfo]"]) -> tuple[str, ...]:
26 classes = (wrapper_cls.start_state_cls, *wrapper_cls.state_classes)
27 return tuple(dict.fromkeys(state_cls.__name__ for state_cls in classes))
30def lost_life(known: int | None, after: RamInfo) -> bool:
31 lives = after.remaining_lives()
32 return known is not None and lives is not None and lives < known
35def known_lives(known: int | None, ram: RamInfo) -> int | None:
36 lives = ram.remaining_lives()
37 return known if lives is None else lives
40class StateMachineGymWrapper(Generic[T]):
41 start_state_cls: ClassVar[type[State[Any]]]
42 state_classes: ClassVar[tuple[type[State[Any]], ...]]
43 ram_info_cls: type[T]
44 action_table: NDArray[np.int8]
45 levels: Levels
47 def __init__(self, env: Console, routes: RouteMap) -> None:
48 if self.action_table.ndim != ACTION_TABLE_DIMENSIONS:
49 raise ValueError("action_table must have the shape (actions, frames, buttons).")
50 level_map(self.levels, self.state_classes)
51 self.ram_info_cls.shown_fields()
52 self.env = env
53 self.routes = routes
54 self.state_machine = StateMachine[T](self.start_state_cls)
56 def read_ram(self) -> T:
57 return self.ram_info_cls.from_ram(self.env.get_ram())