termbluff 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/bin/termbluff.js +80 -0
- package/package.json +9 -4
- package/src/client.js +146 -0
- package/src/server.js +187 -0
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# termbluff
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Liar's Dice** in your terminal: a bluffing and probability game for 2-6 players over LAN or the internet. No dependencies, nothing to install except Node.js 16+.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx termbluff host # host a table and play (prints how friends join)
|
|
7
|
+
npx termbluff join 192.168.1.5 # join (host:port also works)
|
|
8
|
+
npx termbluff # interactive menu
|
|
9
|
+
npx termbluff serve # headless server (VPS)
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## How to play
|
|
13
|
+
Everyone starts with 5 dice, rolled in secret each round. You only see your own.
|
|
14
|
+
|
|
15
|
+
On your turn, either:
|
|
16
|
+
- **Raise the bid**: claim there are at least `q` dice showing face `f` across ALL players' dice. A raise needs a higher quantity, or the same quantity with a higher face.
|
|
17
|
+
- **Call LIAR** on the previous bid. All dice are revealed. If the real count is at least the bid, the bidder was honest and **you** lose a die. Otherwise the bidder loses one.
|
|
18
|
+
|
|
19
|
+
Whoever loses a die starts the next round. At 0 dice you're out. Last player standing wins. Ones are not wild. A turn times out after 40s (auto-bid or auto-challenge).
|
|
20
|
+
|
|
21
|
+
Controls: up/down = quantity, left/right = face, Enter = bid, `L` = call liar, `q` = quit. Terminal at least 60x22.
|
|
22
|
+
|
|
23
|
+
## Over the internet
|
|
24
|
+
Host needs TCP port 7778 (or `--port`) reachable: router port-forward, `serve` on a VPS, or a VPN overlay such as Tailscale/ZeroTier. Connections are unauthenticated plain TCP.
|
|
25
|
+
|
|
26
|
+
## Publish
|
|
27
|
+
`npm login && npm publish`
|
package/bin/termbluff.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const readline = require('readline');
|
|
5
|
+
const { createServer } = require('../src/server');
|
|
6
|
+
const { run } = require('../src/client');
|
|
7
|
+
|
|
8
|
+
const DEFAULT_PORT = 7778;
|
|
9
|
+
|
|
10
|
+
function usage() {
|
|
11
|
+
console.log(`termbluff - Liar's Dice for 2-6 players in your terminal (LAN / internet)
|
|
12
|
+
|
|
13
|
+
npx termbluff interactive menu
|
|
14
|
+
npx termbluff host [--port N] [--name NAME] host a table and play
|
|
15
|
+
npx termbluff join HOST[:PORT] [--name NAME] join someone's table
|
|
16
|
+
npx termbluff serve [--port N] headless dedicated server
|
|
17
|
+
`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const opt = (args, flag, fb) => { const i = args.indexOf(flag); return i >= 0 && args[i + 1] ? args[i + 1] : fb; };
|
|
21
|
+
|
|
22
|
+
function lanIps() {
|
|
23
|
+
const ips = [];
|
|
24
|
+
for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) if (a.family === 'IPv4' && !a.internal) ips.push(a.address);
|
|
25
|
+
return ips;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function parseTarget(t) {
|
|
29
|
+
const m = /^(.+?)(?::(\d+))?$/.exec(t);
|
|
30
|
+
return { host: m[1], port: m[2] ? Number(m[2]) : DEFAULT_PORT };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function ask(q) {
|
|
34
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
35
|
+
return new Promise((res) => rl.question(q, (a) => { rl.close(); res(a.trim()); }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function startServer(port) {
|
|
39
|
+
const srv = createServer({ port });
|
|
40
|
+
srv.server.on('error', (e) => {
|
|
41
|
+
console.error(e.code === 'EADDRINUSE' ? `Port ${port} is already in use (use --port).` : `Server error: ${e.message}`);
|
|
42
|
+
process.exit(1);
|
|
43
|
+
});
|
|
44
|
+
return srv;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function main() {
|
|
48
|
+
const args = process.argv.slice(2);
|
|
49
|
+
let cmd = args[0], target = args[1];
|
|
50
|
+
const name = opt(args, '--name', os.userInfo().username);
|
|
51
|
+
const port = Number(opt(args, '--port', DEFAULT_PORT));
|
|
52
|
+
|
|
53
|
+
if (!cmd) {
|
|
54
|
+
console.log("TERMBLUFF - Liar's Dice\n 1) Host a table\n 2) Join a table\n 3) Quit");
|
|
55
|
+
const c = await ask('> ');
|
|
56
|
+
if (c === '1') cmd = 'host';
|
|
57
|
+
else if (c === '2') { cmd = 'join'; target = await ask('Host address (e.g. 192.168.1.5 or 192.168.1.5:7778): '); }
|
|
58
|
+
else return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (cmd === 'serve') {
|
|
62
|
+
startServer(port).server.on('listening', () =>
|
|
63
|
+
console.log(`termbluff server on port ${port}. LAN: ${lanIps().map((i) => `${i}:${port}`).join(', ') || 'n/a'}`));
|
|
64
|
+
} else if (cmd === 'host') {
|
|
65
|
+
const srv = startServer(port);
|
|
66
|
+
srv.server.on('listening', () => {
|
|
67
|
+
const ip = lanIps()[0] || '<your-ip>';
|
|
68
|
+
run({ host: '127.0.0.1', port, name, info: `Friends join: npx termbluff join ${ip}${port === DEFAULT_PORT ? '' : ':' + port}`,
|
|
69
|
+
onExit: (c) => { srv.close(); process.exit(c); } });
|
|
70
|
+
});
|
|
71
|
+
} else if (cmd === 'join' && target) {
|
|
72
|
+
const t = parseTarget(target);
|
|
73
|
+
run({ host: t.host, port: t.port, name, info: `Connected to ${t.host}:${t.port}`, onExit: process.exit });
|
|
74
|
+
} else {
|
|
75
|
+
usage();
|
|
76
|
+
process.exit(cmd === 'help' || cmd === '--help' ? 0 : 1);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "termbluff",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Liar's Dice - a multiplayer bluffing game that runs entirely in your terminal. LAN or internet. Zero dependencies.",
|
|
5
|
+
"bin": { "termbluff": "bin/termbluff.js" },
|
|
6
|
+
"files": ["bin", "src", "README.md"],
|
|
7
|
+
"scripts": { "test": "node test/smoke.js" },
|
|
8
|
+
"engines": { "node": ">=16" },
|
|
9
|
+
"keywords": ["game", "terminal", "multiplayer", "liars-dice", "bluff", "cli", "lan"],
|
|
10
|
+
"license": "MIT"
|
|
11
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const net = require('net');
|
|
3
|
+
const { validRaise } = require('./server');
|
|
4
|
+
|
|
5
|
+
const safe = (s) => String(s).replace(/[^\x20-\x7e]/g, '?'); // never trust peer text
|
|
6
|
+
const B = (s) => `\x1b[1m${s}\x1b[0m`;
|
|
7
|
+
const DIM = (s) => `\x1b[2m${s}\x1b[0m`;
|
|
8
|
+
const RED = (s) => `\x1b[31m${s}\x1b[0m`;
|
|
9
|
+
const GRN = (s) => `\x1b[32m${s}\x1b[0m`;
|
|
10
|
+
const YEL = (s) => `\x1b[33m${s}\x1b[0m`;
|
|
11
|
+
const die = (d) => `[${d}]`;
|
|
12
|
+
|
|
13
|
+
// Pure: state + local selection -> screen text. Exported for tests.
|
|
14
|
+
function renderFrame(s, sel, info, msg, now = 0) {
|
|
15
|
+
const name = (id) => safe((s.players.find((p) => p.id === id) || {}).name || '?');
|
|
16
|
+
const L = [B("TERMBLUFF - Liar's Dice") + ' ' + DIM(safe(info || '')), ''];
|
|
17
|
+
|
|
18
|
+
for (const p of s.players) {
|
|
19
|
+
const pips = p.alive || s.phase === 'lobby' ? '#'.repeat(p.n) : 'OUT';
|
|
20
|
+
const tag = [p.id === s.me.id ? '(you)' : '', p.id === s.host && s.phase === 'lobby' ? '(host)' : ''].filter(Boolean).join(' ');
|
|
21
|
+
const row = `${p.id === s.turn ? YEL('>') : ' '} ${safe(p.name).padEnd(12)} ${pips.padEnd(6)} ${tag}`;
|
|
22
|
+
L.push(p.alive || s.phase === 'lobby' ? row : DIM(row));
|
|
23
|
+
}
|
|
24
|
+
L.push('');
|
|
25
|
+
|
|
26
|
+
if (s.phase === 'lobby') {
|
|
27
|
+
L.push(s.me.id === s.host
|
|
28
|
+
? (s.players.length < 2 ? 'Waiting for players... (need 2+)' : GRN('Press Enter to start the game'))
|
|
29
|
+
: 'Waiting for the host to start...');
|
|
30
|
+
} else if (s.phase === 'bidding') {
|
|
31
|
+
L.push(`Dice on table: ${B(s.total)} Current bid: ${s.bid ? B(`${s.bid.q} x ${s.bid.f}s`) + ' by ' + name(s.bid.by) : DIM('none')}`);
|
|
32
|
+
L.push('', 'Your dice: ' + (s.me.dice.length ? s.me.dice.map(die).join(' ') : DIM('(out)')), '');
|
|
33
|
+
const secs = Math.max(0, Math.ceil((s.ms - now) / 1000));
|
|
34
|
+
if (s.turn === s.me.id) {
|
|
35
|
+
const ok = validRaise(s.bid, sel.q, sel.f);
|
|
36
|
+
L.push(GRN('YOUR TURN') + ` (${secs}s)`);
|
|
37
|
+
L.push(` Bid: ${(ok ? B : RED)(`${sel.q} x ${sel.f}s`)} ${DIM('up/down = quantity, left/right = face, Enter = bid' + (s.bid ? ', L = call LIAR' : ''))}`);
|
|
38
|
+
} else {
|
|
39
|
+
L.push(`Waiting for ${B(name(s.turn))} ... (${secs}s)`);
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
const r = s.reveal;
|
|
43
|
+
if (r) {
|
|
44
|
+
L.push(B(`${name(r.caller)} called LIAR on ${r.bid.q} x ${r.face}s`), '');
|
|
45
|
+
for (const [id, ds] of Object.entries(r.dice)) {
|
|
46
|
+
L.push(` ${safe(r.names[id]).padEnd(12)} ` + ds.map((d) => (d === r.face ? GRN(die(d)) : die(d))).join(' '));
|
|
47
|
+
}
|
|
48
|
+
L.push('', `Actual count of ${r.face}s: ${B(r.count)} -> ${RED(name(r.loser) + ' loses a die')}`);
|
|
49
|
+
}
|
|
50
|
+
if (s.phase === 'over') L.push('', B(GRN(`*** ${s.winner ? name(s.winner) : 'Nobody'} WINS! ***`)), DIM('Returning to lobby...'));
|
|
51
|
+
else L.push('', DIM('Next round starting...'));
|
|
52
|
+
}
|
|
53
|
+
L.push('', DIM('--- log ---'), ...s.log.slice(-5).map((x) => DIM(safe(x))));
|
|
54
|
+
if (msg) L.push('', RED(safe(msg)));
|
|
55
|
+
L.push('', DIM('q / Ctrl+C = quit'));
|
|
56
|
+
return L.join('\x1b[K\r\n') + '\x1b[K';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function run({ host, port, name, info, onExit = () => {} }) {
|
|
60
|
+
const out = process.stdout, inp = process.stdin;
|
|
61
|
+
if (!inp.isTTY || !out.isTTY) { console.error('termbluff needs an interactive terminal.'); return onExit(1); }
|
|
62
|
+
let state = null, sel = { q: 1, f: 1 }, msg = '', done = false, recvAt = 0, lastKey = '';
|
|
63
|
+
|
|
64
|
+
const sock = net.connect({ host, port });
|
|
65
|
+
sock.setNoDelay(true);
|
|
66
|
+
const send = (o) => { if (!done) sock.write(JSON.stringify(o) + '\n'); };
|
|
67
|
+
const finish = (code, text) => {
|
|
68
|
+
if (done) return;
|
|
69
|
+
done = true;
|
|
70
|
+
clearInterval(tick);
|
|
71
|
+
try { inp.setRawMode(false); } catch {}
|
|
72
|
+
inp.pause();
|
|
73
|
+
out.write('\x1b[?25h\x1b[?1049l');
|
|
74
|
+
if (text) console.log(text);
|
|
75
|
+
sock.destroy();
|
|
76
|
+
onExit(code);
|
|
77
|
+
};
|
|
78
|
+
const draw = () => {
|
|
79
|
+
if (!state) return;
|
|
80
|
+
const cols = out.columns || 80, rows = out.rows || 24;
|
|
81
|
+
if (cols < 60 || rows < 22) { out.write('\x1b[2J\x1b[HTerminal too small (need 60x22). Resize.'); return; }
|
|
82
|
+
// state.ms is time left when sent; rebase to local clock for the countdown
|
|
83
|
+
out.write('\x1b[H' + renderFrame({ ...state, ms: state.ms }, sel, info, msg, Date.now() - recvAt) + '\x1b[J');
|
|
84
|
+
};
|
|
85
|
+
const tick = setInterval(draw, 500);
|
|
86
|
+
|
|
87
|
+
inp.setRawMode(true);
|
|
88
|
+
inp.resume();
|
|
89
|
+
out.write('\x1b[?1049h\x1b[?25l\x1b[2J');
|
|
90
|
+
out.write(`Connecting to ${host}:${port} ...`);
|
|
91
|
+
|
|
92
|
+
const resetSel = () => {
|
|
93
|
+
const b = state.bid;
|
|
94
|
+
sel = !b ? { q: 1, f: 1 } : b.f < 6 ? { q: b.q, f: b.f + 1 } : { q: b.q + 1, f: 1 };
|
|
95
|
+
sel.q = Math.min(sel.q, Math.max(1, state.total));
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
let buf = '';
|
|
99
|
+
sock.on('connect', () => send({ t: 'join', name }));
|
|
100
|
+
sock.on('data', (c) => {
|
|
101
|
+
buf += c;
|
|
102
|
+
let nl;
|
|
103
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
104
|
+
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
|
105
|
+
let m;
|
|
106
|
+
try { m = JSON.parse(line); } catch { return finish(1, 'Protocol error from server.'); }
|
|
107
|
+
if (m.t === 's') {
|
|
108
|
+
const turnChanged = !state || state.turn !== m.turn || state.phase !== m.phase || JSON.stringify(state.bid) !== JSON.stringify(m.bid);
|
|
109
|
+
state = m; recvAt = Date.now(); msg = '';
|
|
110
|
+
if (turnChanged) resetSel();
|
|
111
|
+
draw();
|
|
112
|
+
} else if (m.t === 'err') {
|
|
113
|
+
if (!state) return finish(1, `Server: ${safe(m.msg)}`);
|
|
114
|
+
msg = m.msg; draw();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
sock.on('error', (e) => finish(1, `Connection failed: ${e.code || e.message}`));
|
|
119
|
+
sock.on('close', () => finish(0, 'Disconnected from server.'));
|
|
120
|
+
out.on('resize', () => { out.write('\x1b[2J'); draw(); });
|
|
121
|
+
|
|
122
|
+
inp.on('data', (b) => {
|
|
123
|
+
const s = b.toString();
|
|
124
|
+
const re = /\x1b\[([ABCD])|(\r|\n)|([lLqQ])|(\x03)/g;
|
|
125
|
+
let m;
|
|
126
|
+
while ((m = re.exec(s))) {
|
|
127
|
+
if (m[4] || /[qQ]/.test(m[3] || '')) return finish(0, 'Bye!');
|
|
128
|
+
if (!state) continue;
|
|
129
|
+
if (m[2]) {
|
|
130
|
+
if (state.phase === 'lobby') send({ t: 'start' });
|
|
131
|
+
else if (state.phase === 'bidding' && state.turn === state.me.id) send({ t: 'bid', q: sel.q, f: sel.f });
|
|
132
|
+
} else if (m[3]) {
|
|
133
|
+
if (state.phase === 'bidding' && state.turn === state.me.id) send({ t: 'liar' });
|
|
134
|
+
} else if (state.phase === 'bidding' && state.turn === state.me.id) {
|
|
135
|
+
if (m[1] === 'A') sel.q = Math.min(state.total, sel.q + 1);
|
|
136
|
+
if (m[1] === 'B') sel.q = Math.max(1, sel.q - 1);
|
|
137
|
+
if (m[1] === 'C') sel.f = Math.min(6, sel.f + 1);
|
|
138
|
+
if (m[1] === 'D') sel.f = Math.max(1, sel.f - 1);
|
|
139
|
+
draw();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
process.on('SIGTERM', () => finish(0));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { run, renderFrame };
|
package/src/server.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Liar's Dice server. Authoritative; each client only ever receives its OWN dice
|
|
3
|
+
// until a challenge reveals everyone's. Newline-delimited JSON over TCP.
|
|
4
|
+
// client -> server: join{name} start bid{q,f} liar
|
|
5
|
+
// server -> client: err{msg} | s{...personalised state}
|
|
6
|
+
const net = require('net');
|
|
7
|
+
|
|
8
|
+
const MAX_PLAYERS = 6;
|
|
9
|
+
const START_DICE = 5;
|
|
10
|
+
const MAX_LINE = 1024;
|
|
11
|
+
|
|
12
|
+
const cleanName = (s) => String(s || '').replace(/[^\x20-\x7e]/g, '').trim().slice(0, 12) || 'player';
|
|
13
|
+
const roll = (n) => Array.from({ length: n }, () => 1 + Math.floor(Math.random() * 6));
|
|
14
|
+
const validRaise = (bid, q, f) => !bid || q > bid.q || (q === bid.q && f > bid.f);
|
|
15
|
+
|
|
16
|
+
function createServer({ port = 7778, host = '0.0.0.0', turnMs = 40000, revealMs = 7000 } = {}) {
|
|
17
|
+
const players = new Map();
|
|
18
|
+
let order = [];
|
|
19
|
+
let phase = 'lobby'; // lobby | bidding | reveal | over
|
|
20
|
+
let nextId = 1, hostId = null, turn = null, bid = null, reveal = null, winner = null;
|
|
21
|
+
let deadline = 0, timer = null;
|
|
22
|
+
const log = [];
|
|
23
|
+
const say = (m) => { log.push(m); if (log.length > 30) log.shift(); };
|
|
24
|
+
const alive = () => order.filter((id) => players.get(id)?.alive);
|
|
25
|
+
const total = () => alive().reduce((n, id) => n + players.get(id).n, 0);
|
|
26
|
+
const setTimer = (ms, fn) => { clearTimeout(timer); deadline = Date.now() + ms; timer = setTimeout(fn, ms); };
|
|
27
|
+
const nextAlive = (id) => {
|
|
28
|
+
const a = alive();
|
|
29
|
+
if (!a.length) return null;
|
|
30
|
+
for (let i = 1; i <= order.length; i++) {
|
|
31
|
+
const c = order[(order.indexOf(id) + i) % order.length];
|
|
32
|
+
if (players.get(c)?.alive) return c;
|
|
33
|
+
}
|
|
34
|
+
return a[0];
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function snapshot(p) {
|
|
38
|
+
return JSON.stringify({
|
|
39
|
+
t: 's', phase, host: hostId, turn, bid, total: phase === 'lobby' ? 0 : total(),
|
|
40
|
+
ms: phase === 'bidding' || phase === 'over' || phase === 'reveal' ? Math.max(0, deadline - Date.now()) : 0,
|
|
41
|
+
winner, reveal: phase === 'reveal' || phase === 'over' ? reveal : null, log: log.slice(-8),
|
|
42
|
+
players: [...players.values()].map((q) => ({ id: q.id, name: q.name, n: q.n, alive: q.alive })),
|
|
43
|
+
me: { id: p.id, dice: phase === 'bidding' ? p.dice : [] },
|
|
44
|
+
}) + '\n';
|
|
45
|
+
}
|
|
46
|
+
function broadcast() {
|
|
47
|
+
for (const p of players.values()) {
|
|
48
|
+
if (p.sock.destroyed) continue;
|
|
49
|
+
if (p.sock.writableLength > 1 << 20) p.sock.destroy();
|
|
50
|
+
else p.sock.write(snapshot(p));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function startGame() {
|
|
55
|
+
order = [...players.keys()];
|
|
56
|
+
for (const id of order) Object.assign(players.get(id), { n: START_DICE, alive: true });
|
|
57
|
+
winner = null; reveal = null; log.length = 0;
|
|
58
|
+
say('Game started!');
|
|
59
|
+
startRound(order[0]);
|
|
60
|
+
}
|
|
61
|
+
function startRound(starter) {
|
|
62
|
+
phase = 'bidding'; bid = null; turn = starter; reveal = null;
|
|
63
|
+
for (const id of alive()) { const p = players.get(id); p.dice = roll(p.n); }
|
|
64
|
+
setTimer(turnMs, onTimeout);
|
|
65
|
+
broadcast();
|
|
66
|
+
}
|
|
67
|
+
function endGame(w) {
|
|
68
|
+
phase = 'over'; winner = w; turn = null; bid = null;
|
|
69
|
+
say(`${players.get(w)?.name || 'Nobody'} wins!`);
|
|
70
|
+
setTimer(10000, backToLobby);
|
|
71
|
+
broadcast();
|
|
72
|
+
}
|
|
73
|
+
function backToLobby() {
|
|
74
|
+
phase = 'lobby'; reveal = null; winner = null; order = [];
|
|
75
|
+
for (const [id, p] of players) if (p.sock.destroyed) players.delete(id);
|
|
76
|
+
if (!players.has(hostId)) hostId = players.keys().next().value ?? null;
|
|
77
|
+
for (const p of players.values()) Object.assign(p, { n: START_DICE, alive: false, dice: [] });
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
broadcast();
|
|
80
|
+
}
|
|
81
|
+
function onTimeout() {
|
|
82
|
+
const p = players.get(turn);
|
|
83
|
+
if (!p || phase !== 'bidding') return;
|
|
84
|
+
say(`${p.name} ran out of time.`);
|
|
85
|
+
if (bid) challenge(p); else place(p, 1, 1);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function place(p, q, f) {
|
|
89
|
+
bid = { q, f, by: p.id };
|
|
90
|
+
say(`${p.name} bids ${q} x ${f}s`);
|
|
91
|
+
turn = nextAlive(p.id);
|
|
92
|
+
setTimer(turnMs, onTimeout);
|
|
93
|
+
broadcast();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function challenge(caller) {
|
|
97
|
+
const face = bid.f;
|
|
98
|
+
let count = 0;
|
|
99
|
+
const dice = {};
|
|
100
|
+
for (const id of alive()) {
|
|
101
|
+
const q = players.get(id);
|
|
102
|
+
dice[id] = q.dice;
|
|
103
|
+
count += q.dice.filter((d) => d === face).length;
|
|
104
|
+
}
|
|
105
|
+
const bidder = players.get(bid.by);
|
|
106
|
+
const bidderRight = count >= bid.q;
|
|
107
|
+
const loser = bidderRight ? caller : bidder;
|
|
108
|
+
say(`${caller.name} calls LIAR on ${bid.q} x ${face}s - actual ${count}. ${loser.name} loses a die.`);
|
|
109
|
+
if (loser.alive) {
|
|
110
|
+
loser.n--;
|
|
111
|
+
if (loser.n <= 0) { loser.alive = false; say(`${loser.name} is out!`); }
|
|
112
|
+
}
|
|
113
|
+
reveal = { dice, face, count, bid: { ...bid }, caller: caller.id, loser: loser.id,
|
|
114
|
+
names: Object.fromEntries([...players.values()].map((q) => [q.id, q.name])) };
|
|
115
|
+
phase = 'reveal';
|
|
116
|
+
setTimer(revealMs, () => {
|
|
117
|
+
const a = alive();
|
|
118
|
+
if (a.length <= 1) return endGame(a[0]);
|
|
119
|
+
startRound(loser.alive ? loser.id : nextAlive(loser.id));
|
|
120
|
+
});
|
|
121
|
+
broadcast();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function leave(p) {
|
|
125
|
+
if (phase === 'lobby') {
|
|
126
|
+
players.delete(p.id);
|
|
127
|
+
if (hostId === p.id) hostId = players.keys().next().value ?? null;
|
|
128
|
+
return broadcast();
|
|
129
|
+
}
|
|
130
|
+
if (!p.alive) return broadcast();
|
|
131
|
+
p.alive = false; p.n = 0; p.dice = [];
|
|
132
|
+
say(`${p.name} left.`);
|
|
133
|
+
if (phase === 'bidding') {
|
|
134
|
+
const a = alive();
|
|
135
|
+
if (a.length <= 1) return endGame(a[0]);
|
|
136
|
+
if (turn === p.id) { turn = nextAlive(p.id); setTimer(turnMs, onTimeout); }
|
|
137
|
+
}
|
|
138
|
+
broadcast();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const server = net.createServer((sock) => {
|
|
142
|
+
sock.setNoDelay(true);
|
|
143
|
+
sock.setKeepAlive(true, 15000);
|
|
144
|
+
let me = null, buf = '';
|
|
145
|
+
const joinTimer = setTimeout(() => { if (!me) sock.destroy(); }, 5000);
|
|
146
|
+
const err = (msg) => sock.write(JSON.stringify({ t: 'err', msg }) + '\n');
|
|
147
|
+
|
|
148
|
+
sock.on('data', (chunk) => {
|
|
149
|
+
buf += chunk;
|
|
150
|
+
if (buf.length > MAX_LINE * 4) return sock.destroy();
|
|
151
|
+
let nl;
|
|
152
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
153
|
+
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
|
154
|
+
if (line.length > MAX_LINE) return sock.destroy();
|
|
155
|
+
let m;
|
|
156
|
+
try { m = JSON.parse(line); } catch { return sock.destroy(); }
|
|
157
|
+
if (!m || typeof m !== 'object') continue;
|
|
158
|
+
if (m.t === 'join' && !me) {
|
|
159
|
+
if (phase !== 'lobby') { sock.end(JSON.stringify({ t: 'err', msg: 'game in progress, try again soon' }) + '\n'); return; }
|
|
160
|
+
if (players.size >= MAX_PLAYERS) { sock.end(JSON.stringify({ t: 'err', msg: 'table full' }) + '\n'); return; }
|
|
161
|
+
me = { id: nextId++, name: cleanName(m.name), sock, n: START_DICE, alive: false, dice: [] };
|
|
162
|
+
players.set(me.id, me);
|
|
163
|
+
if (hostId === null) hostId = me.id;
|
|
164
|
+
broadcast();
|
|
165
|
+
} else if (!me) {
|
|
166
|
+
continue;
|
|
167
|
+
} else if (m.t === 'start') {
|
|
168
|
+
if (phase === 'lobby' && me.id === hostId) {
|
|
169
|
+
if (players.size < 2) err('need at least 2 players'); else startGame();
|
|
170
|
+
}
|
|
171
|
+
} else if (m.t === 'bid' && phase === 'bidding' && turn === me.id) {
|
|
172
|
+
const { q, f } = m;
|
|
173
|
+
if (Number.isInteger(q) && Number.isInteger(f) && f >= 1 && f <= 6 && q >= 1 && q <= total() && validRaise(bid, q, f)) place(me, q, f);
|
|
174
|
+
else err('invalid bid: raise the quantity, or keep it and raise the face');
|
|
175
|
+
} else if (m.t === 'liar' && phase === 'bidding' && turn === me.id) {
|
|
176
|
+
if (bid) challenge(me); else err('nothing to challenge yet');
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
sock.on('close', () => { clearTimeout(joinTimer); if (me) leave(me); });
|
|
181
|
+
sock.on('error', () => sock.destroy());
|
|
182
|
+
});
|
|
183
|
+
server.listen(port, host);
|
|
184
|
+
return { server, close() { clearTimeout(timer); for (const p of players.values()) p.sock.destroy(); server.close(); } };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
module.exports = { createServer, validRaise, cleanName };
|