EventCodec
TheEventCodec class converts game events and state snapshots into token sequences for training, and decodes token sequences back into structured records for validation.
Constructor
Number of ticks between automatic state snapshots. Snapshots are always taken at tick 0 and when rule-effect events occur.
Minimum salience level for events to be encoded. Events below this threshold are filtered out.
Methods
encode_snapshot
The game state to encode, including snake position, direction, length, food position, and score.
Token IDs representing the snapshot in format:
SNAP PLAYER X_ Y_ DIR_ LEN_ FOOD X_ Y_ SCORE V_encode_event
The event to encode. Supports INPUT, MOVE, EAT, GROW, FOOD_SPAWN, DIE_WALL, DIE_SELF, and SCORE events.
Token IDs representing the event. Length varies by event type:
- INPUT: 1 token (INPUT_U/D/L/R)
- MOVE: 3 tokens (MOVE, X_, Y_)
- EAT: 1 token
- GROW: 2 tokens (GROW, LEN_)
- FOOD_SPAWN: 3 tokens (FOOD_SPAWN, X_, Y_)
- DIE_WALL/DIE_SELF: 1 token
- SCORE: 2 tokens (SCORE, V_)
encode_tick_events
List of events that occurred in a single tick.
Token IDs with TICK prefix followed by encoded events. Returns empty list if no events meet threshold.
encode_episode
Dictionary mapping tick numbers to lists of events that occurred in that tick.
Dictionary mapping tick numbers to game states at those ticks.
Complete token sequence starting with BOS, containing snapshots and tick events, ending with EOS.
Snapshots are automatically inserted at:
- Tick 0 (episode start)
- Every
snapshot_intervalticks - Any tick with a rule-effect salience event (e.g., death, scoring)
decode
Token IDs to decode.
List of dictionaries, each representing a parsed record with a
type field and relevant data fields.{"type": "BOS"}- Beginning of sequence{"type": "EOS"}- End of sequence{"type": "TICK"}- Tick boundary{"type": "SNAP", "player_x": "X3", "player_y": "Y5", "direction": "DIR_R", "length": "LEN3", "food_x": "X7", "food_y": "Y8", "score_tok": "V2"}- State snapshot{"type": "INPUT", "direction": "INPUT_R"}- Player input{"type": "MOVE", "x": "X4", "y": "Y5"}- Movement{"type": "EAT"}- Food eaten{"type": "GROW", "length": "LEN4"}- Snake growth{"type": "FOOD_SPAWN", "x": "X2", "y": "Y7"}- Food respawn{"type": "DIE_WALL"}or{"type": "DIE_SELF"}- Death events{"type": "SCORE", "value": "V3"}- Score update
