Coverage for src/retrospeedlab/search/ram.py: 94%
71 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-04 02:12 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-04 02:12 +0000
1from dataclasses import dataclass, field, fields, is_dataclass
2from functools import cache
3from typing import Any, ClassVar, Self, final
5import numpy as np
6from numpy.typing import NDArray
8from retrospeedlab.search.route.position import Position
11def ram(address: int) -> Any:
12 return field(default=0, metadata={"address": address, "length": 1})
15def ram_array(address: int, length: int) -> Any:
16 if length < 1:
17 raise ValueError("length must be positive.")
18 return field(default_factory=lambda: [0] * length, metadata={"address": address, "length": length})
21def seen(unseen: Any) -> Any:
22 return field(default=unseen, metadata={"screen": True})
25@dataclass(slots=True, frozen=True)
26class Shown:
27 label: str
28 index: bool
30 def value(self, raw: int | None) -> int | None:
31 if raw is None or not self.index:
32 return raw
33 return raw + 1
36def viewed(shown: dict[str, Shown], raw: dict[str, int | None]) -> dict[str, int | None]:
37 missing = [key for key in shown if key not in raw]
38 if missing:
39 raise ValueError(f"The game memory has no {missing} to show viewers, only {list(raw)}")
40 return {field.label: field.value(raw[key]) for key, field in shown.items()}
43@cache
44def mapped(cls: type) -> dict[str, tuple[int, int]]:
45 name = cls.__name__
46 if not is_dataclass(cls):
47 raise TypeError(f"{name} must be a dataclass to map its RAM")
48 return {
49 f.name: (int(f.metadata["address"]), int(f.metadata["length"]))
50 for f in fields(cls)
51 if "screen" not in f.metadata
52 }
55@cache
56def unread(cls: type) -> dict[str, Any]:
57 if hasattr(cls, "__post_init__") or any("__slots__" in vars(base) for base in cls.__mro__[:-1]):
58 raise TypeError(f"{cls.__name__} must keep its RAM fields in its __dict__, without slots or __post_init__")
59 return {f.name: f.default if "screen" in f.metadata else None for f in fields(cls)}
62class RamInfo:
63 shown: ClassVar[dict[str, Shown]]
65 @classmethod
66 @final
67 def shown_fields(cls) -> dict[str, Shown]:
68 if not hasattr(cls, "shown"):
69 raise TypeError(f"{cls.__name__} must declare shown: the game memory viewers see, by label")
70 return cls.shown
72 @classmethod
73 @final
74 def ram_map(cls) -> dict[str, tuple[int, int]]:
75 return mapped(cls)
77 @classmethod
78 @final
79 def from_ram(cls, raw_ram: bytes | bytearray | NDArray[np.uint8]) -> Self:
80 memory = memoryview(raw_ram).cast("B")
81 read = {
82 name: memory[address] if length == 1 else memory[address : address + length].tolist()
83 for name, (address, length) in cls.ram_map().items()
84 }
85 info = object.__new__(cls)
86 vars(info).update(unread(cls))
87 vars(info).update(read)
88 return info
90 def describe(self) -> dict[str, int]:
91 return {}
93 def position(self) -> Position | None:
94 return None
96 def remaining_lives(self) -> int | None:
97 return None
99 def dynamics(self) -> tuple[int, ...]:
100 return ()
102 def level(self) -> int | None:
103 return None
105 def progress(self) -> int:
106 return 0