back to the school

draw.ts

   1  import { type Ball, type Game, type Paddle, BALL_RADIUS, WINDOW_H, WINDOW_W, ball_rect, paddle_rect } from "./state";
   2  
   3  // Drawing reads the game and returns commands. It changes no field and advances no step.
   4  export type DrawRect = { kind: "rect"; x: number; y: number; w: number; h: number; color: string };
   5  export type DrawCircle = { kind: "circle"; x: number; y: number; r: number; color: string };
   6  export type DrawText = { kind: "text"; x: number; y: number; size: number; text: string; color: string };
   7  export type DrawCommand = DrawRect | DrawCircle | DrawText;
   8  
   9  export function draw_game(game: Game): DrawCommand[] { // draw_game: read the round, paint the frame
  10    return [
  11      ...draw_net(),
  12      draw_paddle(game.left),
  13      draw_paddle(game.right),
  14      draw_ball(game.ball),
  15      ...draw_scores(game),
  16      draw_hint(),
  17    ];
  18  }
  19  
  20  export function draw_net(): DrawCommand[] {
  21    const net: DrawCommand[] = [];
  22    for (let y = 0; y < WINDOW_H; y += 32) {
  23      net.push({ kind: "rect", x: WINDOW_W / 2 - 1, y, w: 2, h: 16, color: "#5a6482" });
  24    }
  25    return net;
  26  }
  27  
  28  export function draw_paddle(p: Paddle): DrawCommand {
  29    const r = paddle_rect(p);
  30    return { kind: "rect", x: r.x, y: r.y, w: r.w, h: r.h, color: "#f0f0f0" };
  31  }
  32  
  33  export function draw_ball(b: Ball): DrawCommand {
  34    return { kind: "circle", x: b.x, y: b.y, r: BALL_RADIUS, color: "#ffd666" };
  35  }
  36  
  37  export function draw_scores(game: Game): DrawCommand[] {
  38    return [
  39      { kind: "text", x: 250, y: 28, size: 40, text: score_text(game.left.score), color: "#f0f0f0" }, // scorepair: left then right
  40      { kind: "text", x: 500, y: 28, size: 40, text: score_text(game.right.score), color: "#f0f0f0" },
  41    ];
  42  }
  43  
  44  export function score_text(score: number): string { // textout: the renderer takes text, the state keeps an int
  45    if (score >= 0 && score <= 9) return String(score);
  46    return "+"; // over: every score above nine shares this glyph
  47  }
  48  
  49  export function draw_hint(): DrawCommand {
  50    return { kind: "text", x: 226, y: WINDOW_H - 30, size: 16, text: "W/S or arrows to move, R to restart", color: "#96a0be" }; // arrows: the keys on screen
  51  }