////// A key, named rather than numbered.////// The runtime translates AWT's `keyCode` into these, so no game code ever mentions a key/// code.///pubenumKeywithEq, Order, ToString {case Leftcase Rightcase Upcase Downcase Spacecase Entercase Escapecase Backspacecase F3case Other(Int32)}mod Key {/// The letters, in the order their key codes run.defalphabet(): String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"////// The letter a key stands for, if it is one of A-Z.////// AWT reports `keyCode`, and for letters those values are ASCII uppercase, so this is a/// conversion rather than a table. It is also why initials are uppercase only: `keyCode`/// carries no shift state.///pubdefletter(k: Key): Option[Char] = matchk {case Key.Other(code) ifcode>=65andcode<=90 => Some(String.charAt(code-65, alphabet()))case_ => None }////// A character that may appear in a name: A-Z or 0-9.////// Two separate lookups rather than one range, because `keyCode` puts the digits well/// below the letters and nothing sensible lies between them. `Scores.clean` accepts the/// same set on the way in from a file, so what can be typed and what can be stored agree.///pubdefnameCharacter(k: Key): Option[Char] = matchletter(k) {case Some(c) => Some(c)case None => Option.map(n -> String.charAt(n, digits()), digit(k)) }/// The digits, in the order their key codes run.defdigits(): String = "0123456789"////// The digit a key stands for, if it is one of the number keys.////// AWT reports `keyCode`, and for the number row those values are ASCII digits, so this/// is a subtraction rather than a table.///pubdefdigit(k: Key): Option[Int32] = matchk {case Key.Other(code) ifcode>=48andcode<=57 => Some(code-48)case_ => None }////// Translates an AWT key code.////// The numbers are `java.awt.event.KeyEvent`'s `VK_` constants, which is also what/// Processing reported -- it passed AWT's codes straight through -- so this table did not/// have to change when the window did.///pubdeffromCode(code: Int32): Key = matchcode {case 8 => Key.Backspacecase 10 => Key.Entercase 27 => Key.Escapecase 32 => Key.Spacecase 37 => Key.Leftcase 38 => Key.Upcase 39 => Key.Rightcase 40 => Key.Downcase 114 => Key.F3case_ => Key.Other(code) }}////// Everything a single simulation step is allowed to know about the input devices.////// `held` is the set of keys down for the whole of this step. `pressed` and `released` are/// the edges since the previous step, so a step can distinguish "the key is down" from "the/// key just went down" without keeping its own history.////// A keyboard and nothing else. There was a pointer here too, carried from the window to/// every step and read by nothing in eight releases -- the cabinet, the rules and the demo/// bot are all played with the arrows. It went when the window did.///pubtypealiasSnapshot = { held = Set[Key], pressed = Set[Key], released = Set[Key]}////// Reading the input devices, as an effect.////// `Input.poll` returns the *same* value every time it is called within one simulation/// step: the runtime captures it once, at the top of the frame, and freezes it. That is/// what makes a run reproducible from a recorded list of snapshots.///pubeffInput {defpoll(): Snapshot}mod Input {////// A snapshot with nothing held.///pubdefempty(): Snapshot = { held = Set.empty(), pressed = Set.empty(), released = Set.empty() }////// Builds a snapshot by comparing the keys held now against the keys held last step.////// The two sets are named because transposing them inverts every edge, turning presses/// into releases.pubdefdiff(previous: {previous = Set[Key]}, current: {current = Set[Key]}): Snapshot = {letbefore = previous#previous;letnow = current#current; { held = now, pressed = Set.difference(now, before), released = Set.difference(before, now) } }////// A snapshot with `keys` held, and all of them treated as newly pressed.////// Convenience for tests and scripted replays.///pubdefholding(keys: List[Key]): Snapshot = {letprev = Set.empty();letcurr = List.toSet(keys);diff(previous = prev, current = curr) }// -- handing one frame's keyboard to several logical ticks ------------------------------////// How many logical ticks are due, given what has accumulated and what may be spent.///pubdefticksDue(accumulated: Int64, perTick: Int64, budget: Int32): Int32 =if (perTick<=0i64oraccumulated<perTick)0else {letdue = accumulated/perTick;if (due>Int32.toInt64(budget))budgetelseOption.getWithDefault(0, Int64.tryToInt32(due)) }////// The same snapshot with its edges removed: still held, but pressed and released nothing.///pubdefsteady(s: Snapshot): Snapshot = {pressed = Set.empty(), released = Set.empty() | s}////// One frame's reading of the keyboard, spread over the `n` ticks it has to drive.////// A frame does not map to a tick. The display runs at whatever rate the machine manages/// and the simulation runs at a fixed one, so a frame may owe several ticks or none.////// Only the first tick gets the edges. A press is a *transition*, and handing the same/// `pressed` set to three catch-up ticks fires it three times -- which for anything/// edge-triggered means the action happens once per stalled frame instead of once per/// press, and for anything that toggles means it can end up back where it started./// The rest of the ticks keep the keys held, because holding is a state and does last.///pubdefacrossTicks(n: Int32, s: Snapshot): List[Snapshot] =if (n<=0) Nil elses :: List.repeat(n-1, steady(s))/// The type of an `Input` interpretation that supplies one snapshot to a computation.typealiasInputHandler[a: Type, b: Type, ef: Eff] = a -> b \ ef - Input////// Interprets `Input` by answering every `poll` with the same snapshot.////// Like `Canvas`, this deliberately has no `@DefaultHandler`: a default of "no keys/// held" would let a test that forgot to supply input pass while asserting on a world/// nobody played.///pubdefhandleWith(s: Snapshot, f: a -> b \ ef): InputHandler[a, b, ef] = input ->run {f(input) } withhandlerInput {defpoll(k) = k(s) }////// Runs `f`, answering every `Input.poll` with the same snapshot.///pubdefrunWith(s: Snapshot, f: Unit -> a \ ef): a \ ef - Input = handleWith(s, f)()}