summaryrefslogtreecommitdiff
path: root/src/state/index.ts
blob: 6999188aac1beb5ff462aaf9589ff17a13941a0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
  BRICK_DISTRIBUTION,
  GAME_SIZE,
  NUM_BRICKS,
  NUM_STARTING_BALLS,
} from "./const";
import { Ball, Brick, GameState, SessionState } from "./types";

export * from "./const";
export * from "./types";

export const createRandomBall = (): Ball => ({
  position: [
    GAME_SIZE.cols / 4 + (Math.random() * GAME_SIZE.cols) / 2,
    GAME_SIZE.rows / 4 + (Math.random() * GAME_SIZE.rows) / 2,
  ],
  velocity: [-1 + Math.random() * 2, 0.5 + Math.random()],
});

const createGameState = () =>
  ({
    paddle: { position: [0, GAME_SIZE.rows - 1] },
    balls: new Array(NUM_STARTING_BALLS)
      .fill(undefined)
      .map(() => createRandomBall()),
    bricks: new Array(NUM_BRICKS)
      .fill(undefined)
      .map((_, i) =>
        Math.random() < BRICK_DISTRIBUTION
          ? ({
              position: [i % GAME_SIZE.cols, Math.floor(i / GAME_SIZE.cols)],
            } as Brick)
          : undefined
      )
      .filter((b) => !!b),
  } satisfies GameState);

export const createLocalSessionState = (sessionId: string) =>
  ({
    sessionId,
    seqno: 0,
    localPlayerGameState: createGameState(),
    remotePlayerGameState: undefined,
    inboundEventQueue: [],
    outboundEventQueue: [],
  } satisfies SessionState);

export const createNetworkedSessionState = (sessionId: string) =>
  ({
    sessionId,
    seqno: 0,
    localPlayerGameState: createGameState(),
    remotePlayerGameState: createGameState(),
    inboundEventQueue: [],
    outboundEventQueue: [],
  } satisfies SessionState);