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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
import readline from "node:readline/promises";
import { advanceStateRemote, Connection, getConnection } from "./connection";
import { advanceStateLocal } from "./game";
import { Action } from "./game/types";
import {
createLocalSessionState,
createNetworkedSessionState,
SessionState,
} from "./state";
import { renderState, createAndBindHandler, prepareTerminal, Key } from "./ui";
export const run = async () => {
let actionQueue: Action[] = [];
const updateAction = (key: Key) => {
if (actionQueue.length > 1) {
actionQueue = actionQueue.slice(1);
}
switch (key) {
case Key.LEFT_ARROW:
actionQueue.push(Action.MOVE_LEFT);
break;
case Key.RIGHT_ARROW:
actionQueue.push(Action.MOVE_RIGHT);
break;
default:
break;
}
};
createAndBindHandler(updateAction, process.exit);
let connection: Connection;
const rl = readline.createInterface(process.stdin, process.stdout);
const solo = ["y", ""].includes(
(await rl.question("Play solo? (Y/n) > ")).trim().toLowerCase()
);
let state: SessionState;
if (!solo) {
state = createNetworkedSessionState("NETWORKED-SESSION");
const host = ["y", ""].includes(
(await rl.question("Host? (Y/n) > ")).trim().toLowerCase()
);
if (host) {
console.log(`Starting the server...`);
connection = await getConnection({ localPort: 9932 });
} else {
const hostname =
(await rl.question("Enter remote hostname [localhost] > ")).trim() ||
"localhost";
connection = await getConnection({ remotePort: 9932, hostname });
}
try {
} catch {}
} else {
state = createLocalSessionState("LOCAL-GAME");
}
prepareTerminal();
while (true) {
let nextAction = actionQueue.pop();
state = await advanceStateLocal(state, nextAction);
if (state.remotePlayerGameState) {
connection!.sendState(state);
state = await advanceStateRemote(connection!, state);
}
renderState(state);
}
};
run().then(console.log).catch(console.error);
|