back to the school

input.ts

   1  // Input is a snapshot of the keys at one frame. Nothing else in the game reads a key.
   2  export type Input = { // snapshot: three flags, sampled once per frame
   3    left_up: boolean;
   4    left_down: boolean;
   5    restart: boolean;
   6  };
   7  
   8  export interface KeyReader { // edge: a held key and a press edge are different questions
   9    down(code: string): boolean;
  10    pressed(code: string): boolean;
  11  }
  12  
  13  export function read_input(keys: KeyReader): Input {
  14    return {
  15      left_up: keys.down("KeyW") || keys.down("ArrowUp"), // UP: W or the up arrow moves the left paddle up
  16      left_down: keys.down("KeyS") || keys.down("ArrowDown"),
  17      restart: keys.pressed("KeyR"), // pressedge: R clears the score on the press edge
  18    };
  19  }
  20  
  21  export function direction_of(input: Input): number {
  22    let direction = 0;
  23    if (input.left_up) direction -= 1;
  24    if (input.left_down) direction += 1;
  25    return direction;
  26  }