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);