Files
functional-programming-snake/js/solutions/replay.js
T
Lucas WintherandClaude Fable 5.2 edd57f0148 feat(course): audit fixes and twelve extensions (Modules 7b, 12, 13)
Audit pass:
- Frame rule counts frames since the last move, so every step lasts
  exactly movesEvery(score) frames, also right after a speed-up
- clampTime + MAX_GAP_MS: a hidden tab no longer replays the whole gap
- Pong Restart keeps held keys
- Fact corrections (mulberry32 output coverage, Haskell IO, uniform)
- New fixture cases from a mutation analysis

Extensions (all three tracks, shared fixtures, course text):
- Turn queue (Exercise 10.6), persisted high score (10.7),
  replay viewer (10.8), play() end-to-end helper (9.5)
- Optional State (4.7) and optional Module 7b, stack-safe IO
- Module 12, property-based testing with generators, shrinking,
  invariants and a model-based oracle
- Module 13, Conway's Life with a Click event
- JS type checking via jsconfig, JSDoc and types.d.ts
- Maintainer tools: scripts/mutate.mjs, scripts/typecheck-js.sh,
  Playwright end-to-end suite (e2e/, scripts/e2e.sh)

Docs: docs/contract.md is the canonical contract; specs and build log
under docs/superpowers.

Verified: JS 728, Scala 689, F# 691 unit tests; stubs and progression
M01-M13 and M07b; 176 end-to-end tests on Chromium and WebKit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 12:05:29 +01:00

111 lines
4.9 KiB
JavaScript

// m10 replay viewer: a recorded game is a seed and a list of actions; watching it is a second, tiny program
// whose state is only a position in the list of the game's states.
import { history } from './game.js'
import { newGame } from './spawn.js'
import { view, CELL } from './view.js'
import { pure, drawScene } from './io.js'
import { keyDowns, interval, map, filterMap, merge, scan, startWith, clampTime } from './stream.js'
import { MAX_GAP_MS } from './app.js'
/** @import { GameState, Scene, Stream, Recording, Program } from './types' */
/** @typedef {{index: number, last: number, playing: boolean}} Viewer */
/** @typedef {{tag: 'Next'} | {tag: 'Prev'} | {tag: 'First'} | {tag: 'Last'} | {tag: 'TogglePlay'} | {tag: 'Beat'}} ViewerAction */
/** Milliseconds between two frames of autoplay. */
export const REPLAY_MS = 100
/** Every state of the recorded game, from the new game to the end: the recording replayed with `history`.
* @type {(recording: Recording) => GameState[]} */
export const frames = (recording) => history(newGame(recording.seed), recording.actions)
/** The viewer at the first frame, not playing. `last` is the index of the last frame (the number of actions).
* @type {(last: number) => Viewer} */
export const viewerStart = (last) => ({ index: 0, last, playing: false })
/** Everything the viewer can be asked to do, as data. `Beat` is one beat of the autoplay clock.
* @type {{Next: ViewerAction, Prev: ViewerAction, First: ViewerAction, Last: ViewerAction, TogglePlay: ViewerAction, Beat: ViewerAction}} */
export const ViewerAction = {
Next: { tag: 'Next' },
Prev: { tag: 'Prev' },
First: { tag: 'First' },
Last: { tag: 'Last' },
TogglePlay: { tag: 'TogglePlay' },
Beat: { tag: 'Beat' },
}
const clampIndex = (viewer, index) => Math.min(viewer.last, Math.max(0, index))
// Where each action moves the viewer, and whether it plays afterwards (before the end-of-recording rule).
const move = (viewer, action) => {
switch (action.tag) {
case 'Next': return { ...viewer, index: clampIndex(viewer, viewer.index + 1) }
case 'Prev': return { ...viewer, index: clampIndex(viewer, viewer.index - 1) }
case 'First': return { ...viewer, index: 0 }
case 'Last': return { ...viewer, index: viewer.last }
// Play from the end means: watch it again from the start.
case 'TogglePlay':
return viewer.playing ? { ...viewer, playing: false }
: { ...viewer, index: viewer.index === viewer.last ? 0 : viewer.index, playing: true }
case 'Beat': return viewer.playing ? { ...viewer, index: clampIndex(viewer, viewer.index + 1) } : viewer
default: return viewer
}
}
/**
* One step of the viewer. Total: the index never leaves `[0, last]`, and the viewer never plays on the last frame,
* so autoplay stops by itself at the end.
* @type {(viewer: Viewer, action: ViewerAction) => Viewer}
*/
export const viewerUpdate = (viewer, action) => {
const next = move(viewer, action)
return { ...next, playing: next.playing && next.index < next.last }
}
const keys = {
ArrowRight: ViewerAction.Next, d: ViewerAction.Next, D: ViewerAction.Next,
ArrowLeft: ViewerAction.Prev, a: ViewerAction.Prev, A: ViewerAction.Prev,
Home: ViewerAction.First,
End: ViewerAction.Last,
' ': ViewerAction.TogglePlay,
}
/** A key to a viewer action, or null.
* @type {(key: string) => ViewerAction | null} */
export const viewerKey = (key) => (Object.hasOwn(keys, key) ? keys[key] : null)
/** The game's own picture of the current frame, then the position at the top right and a hint at the bottom.
* @type {(frames: GameState[], viewer: Viewer) => Scene} */
export const viewerView = (frames, viewer) => {
const game = frames[viewer.index]
const w = game.width * CELL
return [
...view(game),
{ tag: 'Text', x: w - 6, y: 18, text: `step ${viewer.index} / ${viewer.last}`, color: '#ffffff', size: 16, align: 'right' },
{
tag: 'Text', x: w / 2, y: game.height * CELL - 8,
text: viewer.playing ? 'Space: pause' : 'Left/Right: step Home/End: jump Space: play',
color: '#aaaaaa', size: 12, align: 'center',
},
]
}
/** Beats every REPLAY_MS, merged with the viewer's keys.
* @type {Stream<ViewerAction>} */
export const replayActions = merge(
map(interval(REPLAY_MS), () => ViewerAction.Beat),
filterMap(keyDowns, viewerKey))
/** The viewer over time: the start first, then one viewer per action.
* @type {(last: number, actions: Stream<ViewerAction>) => Stream<Viewer>} */
export const viewerStates = (last, actions) =>
startWith(scan(actions, viewerUpdate, viewerStart(last)), viewerStart(last))
/**
* The whole viewer as a value. It needs no seed from the world (the recording has one), so it starts with `pure`.
* The frames are computed once, here, and every drawing picks one of them.
* @type {(recording: Recording) => Program}
*/
export const replayMain = (recording) => {
const fs = frames(recording)
return pure(clampTime(map(viewerStates(fs.length - 1, replayActions), (v) => drawScene(viewerView(fs, v))), MAX_GAP_MS))
}