back to the school
state.ts
1 // The whole game is data. No function here draws, reads a key or sleeps.
2 export type Vec2 = { x: number; y: number }; // vector: one position or velocity in two numbers
3 export type Rect = Vec2 & { w: number; h: number };
4 export type Paddle = Vec2 & { score: number };
5 export type Ball = Vec2 & { vx: number; vy: number; wait: number }; // waitfield: steps left before the serve velocity is set
6 export type Game = { // aggregate: one value holds the whole round
7 left: Paddle;
8 right: Paddle;
9 ball: Ball;
10 accumulator: number;
11 serving_to_right: boolean; // sideflag: true sends the ball toward the right paddle
12 };
13
14 export const WINDOW_W = 800;
15 export const WINDOW_H = 450;
16 export const PADDLE_W = 14;
17 export const PADDLE_H = 84;
18 export const PADDLE_SPEED = 360;
19 export const BALL_RADIUS = 7;
20 export const BALL_SPEED = 330;
21 export const SERVE_DELAY_STEPS = 24; // 24: the centre pause after a goal
22
23 export function init_game(): Game {
24 const game: Game = {
25 left: { x: 36, y: (WINDOW_H - PADDLE_H) / 2, score: 0 },
26 right: { x: WINDOW_W - 36 - PADDLE_W, y: (WINDOW_H - PADDLE_H) / 2, score: 0 },
27 ball: { x: 0, y: 0, vx: 0, vy: 0, wait: 0 },
28 accumulator: 0,
29 serving_to_right: true,
30 };
31 serve(game, true);
32 return game;
33 }
34
35 export function serve(game: Game, to_right: boolean): void {
36 game.serving_to_right = to_right;
37 game.ball.x = WINDOW_W / 2;
38 game.ball.y = WINDOW_H / 2;
39 game.ball.vx = 0;
40 game.ball.vy = 0;
41 game.ball.wait = SERVE_DELAY_STEPS;
42 }
43
44 export function start_round(game: Game): void {
45 const dir: number = game.serving_to_right ? 1 : -1;
46 game.ball.vx = dir * BALL_SPEED; // leftbound: a false flag keeps dir negative, so the ball travels left
47 game.ball.vy = BALL_SPEED * 0.35;
48 game.ball.wait = 0;
49 }
50
51 export function paddle_rect(p: Paddle): Rect {
52 return { x: p.x, y: p.y, w: PADDLE_W, h: PADDLE_H };
53 }
54
55 export function ball_rect(b: Ball): Rect {
56 return { x: b.x - BALL_RADIUS, y: b.y - BALL_RADIUS, w: BALL_RADIUS * 2, h: BALL_RADIUS * 2 };
57 }
58
59 export function overlaps(a: Rect, b: Rect): boolean {
60 return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
61 }
62
63 export function clamp(v: number, lo: number, hi: number): number {
64 if (v < lo) return lo;
65 if (v > hi) return hi;
66 return v;
67 }