termbluff 0.0.0-stage → 1.1.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 +28 -2
- package/bin/termbluff.js +97 -0
- package/package.json +30 -4
- package/src/client.js +150 -0
- package/src/online.js +111 -0
- package/src/server.js +189 -0
package/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
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; shows a ROOM CODE like A4VQ66
|
|
7
|
+
npx termbluff join A4VQ66 # friend joins with just the code (internet)
|
|
8
|
+
npx termbluff join 192.168.1.5 # or direct IP[:port] on a LAN
|
|
9
|
+
npx termbluff # interactive menu
|
|
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 (office-friendly)
|
|
24
|
+
Host and joiners both connect **outbound** to a free public MQTT relay over WSS (port 8884/8084/8081), so nobody needs a public IP, port-forwarding, VPN, account or signup. The host picks the first relay reachable from their network and encodes it in the room code.
|
|
25
|
+
|
|
26
|
+
Caveats: the relay is shared infrastructure, so treat the room code as a secret and do not expect privacy beyond that. Game traffic is not encrypted end to end. If an office firewall blocks every relay port the host sees "Relay unreachable"; use a phone hotspot or `serve` on a VPS as a fallback.
|
|
27
|
+
|
|
28
|
+
## Publish
|
|
29
|
+
`npm login && npm publish`
|
package/bin/termbluff.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
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
|
+
const { hostRelay, onlineSocket, isRoomCode } = require('../src/online');
|
|
8
|
+
|
|
9
|
+
const DEFAULT_PORT = 7778;
|
|
10
|
+
|
|
11
|
+
function usage() {
|
|
12
|
+
console.log(`termbluff - Liar's Dice for 2-6 players in your terminal
|
|
13
|
+
|
|
14
|
+
npx termbluff host [--name NAME] [--offline] host a table; prints a ROOM CODE
|
|
15
|
+
npx termbluff join ROOMCODE [--name NAME] join over the internet (no IP/VPN needed)
|
|
16
|
+
npx termbluff join HOST[:PORT] join directly over LAN / known IP
|
|
17
|
+
npx termbluff serve [--port N] headless dedicated server (TCP)
|
|
18
|
+
npx termbluff interactive menu
|
|
19
|
+
|
|
20
|
+
Internet play connects both sides OUT to a free public relay: no signup, no
|
|
21
|
+
port-forwarding, works through typical office firewalls (outbound HTTPS/WSS).
|
|
22
|
+
`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const opt = (args, flag, fb) => { const i = args.indexOf(flag); return i >= 0 && args[i + 1] ? args[i + 1] : fb; };
|
|
26
|
+
|
|
27
|
+
function lanIps() {
|
|
28
|
+
const ips = [];
|
|
29
|
+
for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) if (a.family === 'IPv4' && !a.internal) ips.push(a.address);
|
|
30
|
+
return ips;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function parseTarget(t) {
|
|
34
|
+
const m = /^(.+?)(?::(\d+))?$/.exec(t);
|
|
35
|
+
return { host: m[1], port: m[2] ? Number(m[2]) : DEFAULT_PORT };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function ask(q) {
|
|
39
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
40
|
+
return new Promise((res) => rl.question(q, (a) => { rl.close(); res(a.trim()); }));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function startServer(port, host) {
|
|
44
|
+
const srv = createServer({ port, host });
|
|
45
|
+
srv.server.on('error', (e) => {
|
|
46
|
+
console.error(e.code === 'EADDRINUSE' ? `Port ${port} is already in use (use --port).` : `Server error: ${e.message}`);
|
|
47
|
+
process.exit(1);
|
|
48
|
+
});
|
|
49
|
+
return srv;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function main() {
|
|
53
|
+
const args = process.argv.slice(2);
|
|
54
|
+
let cmd = args[0], target = args[1];
|
|
55
|
+
const name = opt(args, '--name', os.userInfo().username);
|
|
56
|
+
const port = Number(opt(args, '--port', DEFAULT_PORT));
|
|
57
|
+
const offline = args.includes('--offline');
|
|
58
|
+
|
|
59
|
+
if (!cmd) {
|
|
60
|
+
console.log("TERMBLUFF - Liar's Dice\n 1) Host a table\n 2) Join a table\n 3) Quit");
|
|
61
|
+
const c = await ask('> ');
|
|
62
|
+
if (c === '1') cmd = 'host';
|
|
63
|
+
else if (c === '2') { cmd = 'join'; target = await ask('Room code (or host address): '); }
|
|
64
|
+
else return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (cmd === 'serve') {
|
|
68
|
+
startServer(port, '0.0.0.0').server.on('listening', () =>
|
|
69
|
+
console.log(`termbluff server on port ${port}. LAN: ${lanIps().map((i) => `${i}:${port}`).join(', ') || 'n/a'}`));
|
|
70
|
+
} else if (cmd === 'host') {
|
|
71
|
+
// Local player talks to a loopback-only server; remote players arrive via the
|
|
72
|
+
// online relay (outbound only) and, with --offline, optionally over LAN.
|
|
73
|
+
const srv = startServer(port, offline ? '0.0.0.0' : '127.0.0.1');
|
|
74
|
+
let relay = null, status = offline ? `LAN: join ${lanIps()[0] || '<ip>'}:${port}` : 'Connecting to relay...';
|
|
75
|
+
srv.server.on('listening', () => {
|
|
76
|
+
if (!offline) {
|
|
77
|
+
hostRelay(srv.attach)
|
|
78
|
+
.then((r) => { relay = r; status = r ? `ROOM CODE: ${r.code} (friend runs: npx termbluff join ${r.code})` : 'Relay unreachable - this network blocks it'; })
|
|
79
|
+
.catch((e) => { status = `Relay error: ${e.message}`; });
|
|
80
|
+
}
|
|
81
|
+
run({ host: '127.0.0.1', port, name, info: () => status,
|
|
82
|
+
onExit: (c) => { if (relay) relay.close(); srv.close(); process.exit(c); } });
|
|
83
|
+
});
|
|
84
|
+
} else if (cmd === 'join' && target) {
|
|
85
|
+
if (isRoomCode(target) && !offline) {
|
|
86
|
+
run({ name, info: `Room ${target.toUpperCase()}`, connect: () => onlineSocket(target), onExit: process.exit });
|
|
87
|
+
} else {
|
|
88
|
+
const t = parseTarget(target);
|
|
89
|
+
run({ host: t.host, port: t.port, name, info: `Connected to ${t.host}:${t.port}`, onExit: process.exit });
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
usage();
|
|
93
|
+
process.exit(cmd === 'help' || cmd === '--help' ? 0 : 1);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "termbluff",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Liar's Dice - multiplayer bluffing game in your terminal. Play over the internet with a room code: no signup, no IP, no VPN.",
|
|
5
|
+
"bin": {
|
|
6
|
+
"termbluff": "bin/termbluff.js"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"bin",
|
|
10
|
+
"src",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node test/smoke.js"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=16"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"game",
|
|
21
|
+
"terminal",
|
|
22
|
+
"multiplayer",
|
|
23
|
+
"liars-dice",
|
|
24
|
+
"bluff",
|
|
25
|
+
"cli",
|
|
26
|
+
"lan"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"mqtt": "^5.16.1"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
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
|
+
// `connect` optionally supplies a socket-like stream (used for online rooms);
|
|
60
|
+
// `info` may be a string or a function returning one.
|
|
61
|
+
function run({ host, port, name, info, connect, onExit = () => {} }) {
|
|
62
|
+
const out = process.stdout, inp = process.stdin;
|
|
63
|
+
if (!inp.isTTY || !out.isTTY) { console.error('termbluff needs an interactive terminal.'); return onExit(1); }
|
|
64
|
+
let state = null, sel = { q: 1, f: 1 }, msg = '', done = false, recvAt = 0, lastKey = '';
|
|
65
|
+
|
|
66
|
+
const sock = connect ? connect() : net.connect({ host, port });
|
|
67
|
+
sock.setNoDelay(true);
|
|
68
|
+
const noReply = setTimeout(() => { if (!state) finish(1, 'No response - wrong room code, or the host is not running.'); }, 15000);
|
|
69
|
+
const send = (o) => { if (!done) sock.write(JSON.stringify(o) + '\n'); };
|
|
70
|
+
const finish = (code, text) => {
|
|
71
|
+
if (done) return;
|
|
72
|
+
done = true;
|
|
73
|
+
clearInterval(tick);
|
|
74
|
+
clearTimeout(noReply);
|
|
75
|
+
try { inp.setRawMode(false); } catch {}
|
|
76
|
+
inp.pause();
|
|
77
|
+
out.write('\x1b[?25h\x1b[?1049l');
|
|
78
|
+
if (text) console.log(text);
|
|
79
|
+
sock.destroy();
|
|
80
|
+
onExit(code);
|
|
81
|
+
};
|
|
82
|
+
const draw = () => {
|
|
83
|
+
if (!state) return;
|
|
84
|
+
const cols = out.columns || 80, rows = out.rows || 24;
|
|
85
|
+
if (cols < 60 || rows < 22) { out.write('\x1b[2J\x1b[HTerminal too small (need 60x22). Resize.'); return; }
|
|
86
|
+
// state.ms is time left when sent; rebase to local clock for the countdown
|
|
87
|
+
out.write('\x1b[H' + renderFrame({ ...state, ms: state.ms }, sel, typeof info === 'function' ? info() : info, msg, Date.now() - recvAt) + '\x1b[J');
|
|
88
|
+
};
|
|
89
|
+
const tick = setInterval(draw, 500);
|
|
90
|
+
|
|
91
|
+
inp.setRawMode(true);
|
|
92
|
+
inp.resume();
|
|
93
|
+
out.write('\x1b[?1049h\x1b[?25l\x1b[2J');
|
|
94
|
+
out.write(connect ? 'Connecting to online room ...' : `Connecting to ${host}:${port} ...`);
|
|
95
|
+
|
|
96
|
+
const resetSel = () => {
|
|
97
|
+
const b = state.bid;
|
|
98
|
+
sel = !b ? { q: 1, f: 1 } : b.f < 6 ? { q: b.q, f: b.f + 1 } : { q: b.q + 1, f: 1 };
|
|
99
|
+
sel.q = Math.min(sel.q, Math.max(1, state.total));
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
let buf = '';
|
|
103
|
+
sock.on('connect', () => send({ t: 'join', name }));
|
|
104
|
+
sock.on('data', (c) => {
|
|
105
|
+
buf += c;
|
|
106
|
+
let nl;
|
|
107
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
108
|
+
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
|
109
|
+
let m;
|
|
110
|
+
try { m = JSON.parse(line); } catch { return finish(1, 'Protocol error from server.'); }
|
|
111
|
+
if (m.t === 's') {
|
|
112
|
+
const turnChanged = !state || state.turn !== m.turn || state.phase !== m.phase || JSON.stringify(state.bid) !== JSON.stringify(m.bid);
|
|
113
|
+
state = m; recvAt = Date.now(); msg = '';
|
|
114
|
+
if (turnChanged) resetSel();
|
|
115
|
+
draw();
|
|
116
|
+
} else if (m.t === 'err') {
|
|
117
|
+
if (!state) return finish(1, `Server: ${safe(m.msg)}`);
|
|
118
|
+
msg = m.msg; draw();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
sock.on('error', (e) => finish(1, `Connection failed: ${e.code || e.message}`));
|
|
123
|
+
sock.on('close', () => finish(0, 'Disconnected from server.'));
|
|
124
|
+
out.on('resize', () => { out.write('\x1b[2J'); draw(); });
|
|
125
|
+
|
|
126
|
+
inp.on('data', (b) => {
|
|
127
|
+
const s = b.toString();
|
|
128
|
+
const re = /\x1b\[([ABCD])|(\r|\n)|([lLqQ])|(\x03)/g;
|
|
129
|
+
let m;
|
|
130
|
+
while ((m = re.exec(s))) {
|
|
131
|
+
if (m[4] || /[qQ]/.test(m[3] || '')) return finish(0, 'Bye!');
|
|
132
|
+
if (!state) continue;
|
|
133
|
+
if (m[2]) {
|
|
134
|
+
if (state.phase === 'lobby') send({ t: 'start' });
|
|
135
|
+
else if (state.phase === 'bidding' && state.turn === state.me.id) send({ t: 'bid', q: sel.q, f: sel.f });
|
|
136
|
+
} else if (m[3]) {
|
|
137
|
+
if (state.phase === 'bidding' && state.turn === state.me.id) send({ t: 'liar' });
|
|
138
|
+
} else if (state.phase === 'bidding' && state.turn === state.me.id) {
|
|
139
|
+
if (m[1] === 'A') sel.q = Math.min(state.total, sel.q + 1);
|
|
140
|
+
if (m[1] === 'B') sel.q = Math.max(1, sel.q - 1);
|
|
141
|
+
if (m[1] === 'C') sel.f = Math.min(6, sel.f + 1);
|
|
142
|
+
if (m[1] === 'D') sel.f = Math.max(1, sel.f - 1);
|
|
143
|
+
draw();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
process.on('SIGTERM', () => finish(0));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
module.exports = { run, renderFrame };
|
package/src/online.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Internet play without public IPs, VPNs or port-forwarding: host and joiners both
|
|
3
|
+
// connect OUT to a public MQTT broker over WSS, and the game's normal JSON lines
|
|
4
|
+
// travel through it. Room code = broker letter + 5 random chars, e.g. "A7K3QZ".
|
|
5
|
+
const { Duplex } = require('stream');
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
|
|
8
|
+
const BROKERS = [
|
|
9
|
+
'wss://broker.hivemq.com:8884/mqtt',
|
|
10
|
+
'wss://broker.emqx.io:8084/mqtt',
|
|
11
|
+
'wss://test.mosquitto.org:8081',
|
|
12
|
+
];
|
|
13
|
+
const ALPHA = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
14
|
+
const CODE_RE = /^[A-C][A-HJ-NP-Z2-9]{5}$/;
|
|
15
|
+
const PING_MS = 5000;
|
|
16
|
+
const IDLE_MS = 20000;
|
|
17
|
+
const BYE = '{"t":"bye"}\n';
|
|
18
|
+
const PING = '{"t":"ping"}\n';
|
|
19
|
+
|
|
20
|
+
const isRoomCode = (s) => CODE_RE.test(String(s || '').toUpperCase());
|
|
21
|
+
const stub = (sock) => { sock.setNoDelay = () => {}; sock.setKeepAlive = () => {}; return sock; };
|
|
22
|
+
|
|
23
|
+
function connectBroker(url) {
|
|
24
|
+
const mqtt = require('mqtt');
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const c = mqtt.connect(url, { protocolVersion: 4, connectTimeout: 8000, reconnectPeriod: 0, clientId: 'tb_' + crypto.randomBytes(6).toString('hex') });
|
|
27
|
+
c.once('connect', () => { c.removeAllListeners('error'); resolve(c); });
|
|
28
|
+
c.once('error', (e) => { c.end(true); reject(e); });
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const subscribe = (c, topic) => new Promise((res, rej) => c.subscribe(topic, { qos: 1 }, (e) => (e ? rej(e) : res())));
|
|
32
|
+
|
|
33
|
+
// Host side: every remote player becomes a virtual socket handed to the game server.
|
|
34
|
+
async function hostRelay(attach) {
|
|
35
|
+
for (let i = 0; i < BROKERS.length; i++) {
|
|
36
|
+
let c;
|
|
37
|
+
try { c = await connectBroker(BROKERS[i]); } catch { continue; }
|
|
38
|
+
const code = String.fromCharCode(65 + i) + Array.from(crypto.randomBytes(5), (b) => ALPHA[b % ALPHA.length]).join('');
|
|
39
|
+
const base = `termbluff/v1/${code}`;
|
|
40
|
+
try { await subscribe(c, `${base}/up/+`); } catch { c.end(true); continue; }
|
|
41
|
+
const conns = new Map();
|
|
42
|
+
|
|
43
|
+
c.on('message', (topic, payload) => {
|
|
44
|
+
const cid = topic.split('/').pop();
|
|
45
|
+
let e = conns.get(cid);
|
|
46
|
+
const text = payload.toString();
|
|
47
|
+
if (!e) {
|
|
48
|
+
if (text.includes('"bye"')) return;
|
|
49
|
+
const sock = stub(new Duplex({
|
|
50
|
+
read() {},
|
|
51
|
+
write(chunk, _enc, cb) { c.publish(`${base}/down/${cid}`, chunk.toString(), { qos: 1 }, () => cb()); },
|
|
52
|
+
final(cb) { cb(); setImmediate(() => sock.destroy()); },
|
|
53
|
+
}));
|
|
54
|
+
e = { sock, seen: Date.now() };
|
|
55
|
+
conns.set(cid, e);
|
|
56
|
+
sock.on('close', () => conns.delete(cid));
|
|
57
|
+
sock.on('error', () => {});
|
|
58
|
+
attach(sock);
|
|
59
|
+
}
|
|
60
|
+
e.seen = Date.now();
|
|
61
|
+
if (text.includes('"bye"')) return e.sock.destroy();
|
|
62
|
+
e.sock.push(text);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const sweep = setInterval(() => {
|
|
66
|
+
for (const e of conns.values()) if (Date.now() - e.seen > IDLE_MS) e.sock.destroy();
|
|
67
|
+
}, PING_MS);
|
|
68
|
+
c.on('close', () => clearInterval(sweep));
|
|
69
|
+
return { code, close() { clearInterval(sweep); for (const e of conns.values()) e.sock.destroy(); c.end(true); } };
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Joiner side: a socket-like Duplex that emits 'connect' once it is wired to the room.
|
|
75
|
+
function onlineSocket(rawCode) {
|
|
76
|
+
const code = rawCode.toUpperCase();
|
|
77
|
+
const url = BROKERS[code.charCodeAt(0) - 65];
|
|
78
|
+
const cid = crypto.randomBytes(6).toString('hex');
|
|
79
|
+
const base = `termbluff/v1/${code}`;
|
|
80
|
+
let c = null, pingT = null;
|
|
81
|
+
const sock = stub(new Duplex({
|
|
82
|
+
read() {},
|
|
83
|
+
write(chunk, _enc, cb) {
|
|
84
|
+
if (!c || !c.connected) return cb();
|
|
85
|
+
c.publish(`${base}/up/${cid}`, chunk.toString(), { qos: 1 }, () => cb());
|
|
86
|
+
},
|
|
87
|
+
destroy(err, cb) {
|
|
88
|
+
clearInterval(pingT);
|
|
89
|
+
const client = c; c = null;
|
|
90
|
+
if (client) {
|
|
91
|
+
const end = () => client.end(true);
|
|
92
|
+
client.connected ? client.publish(`${base}/up/${cid}`, BYE, { qos: 1 }, end) : end();
|
|
93
|
+
setTimeout(end, 1500).unref();
|
|
94
|
+
}
|
|
95
|
+
cb(err);
|
|
96
|
+
},
|
|
97
|
+
}));
|
|
98
|
+
connectBroker(url)
|
|
99
|
+
.then(async (client) => {
|
|
100
|
+
c = client;
|
|
101
|
+
client.on('message', (_t, p) => sock.push(p.toString()));
|
|
102
|
+
client.on('close', () => sock.destroy());
|
|
103
|
+
await subscribe(client, `${base}/down/${cid}`);
|
|
104
|
+
pingT = setInterval(() => client.connected && client.publish(`${base}/up/${cid}`, PING, { qos: 0 }), PING_MS);
|
|
105
|
+
sock.emit('connect');
|
|
106
|
+
})
|
|
107
|
+
.catch((e) => sock.destroy(e));
|
|
108
|
+
return sock;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { hostRelay, onlineSocket, isRoomCode, BROKERS };
|
package/src/server.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
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
|
+
// onConn handles any duplex stream: real TCP sockets and the online relay's virtual ones.
|
|
142
|
+
const onConn = (sock) => {
|
|
143
|
+
sock.setNoDelay(true);
|
|
144
|
+
sock.setKeepAlive(true, 15000);
|
|
145
|
+
let me = null, buf = '';
|
|
146
|
+
const joinTimer = setTimeout(() => { if (!me) sock.destroy(); }, 5000);
|
|
147
|
+
const err = (msg) => sock.write(JSON.stringify({ t: 'err', msg }) + '\n');
|
|
148
|
+
|
|
149
|
+
sock.on('data', (chunk) => {
|
|
150
|
+
buf += chunk;
|
|
151
|
+
if (buf.length > MAX_LINE * 4) return sock.destroy();
|
|
152
|
+
let nl;
|
|
153
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
154
|
+
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
|
155
|
+
if (line.length > MAX_LINE) return sock.destroy();
|
|
156
|
+
let m;
|
|
157
|
+
try { m = JSON.parse(line); } catch { return sock.destroy(); }
|
|
158
|
+
if (!m || typeof m !== 'object') continue;
|
|
159
|
+
if (m.t === 'join' && !me) {
|
|
160
|
+
if (phase !== 'lobby') { sock.end(JSON.stringify({ t: 'err', msg: 'game in progress, try again soon' }) + '\n'); return; }
|
|
161
|
+
if (players.size >= MAX_PLAYERS) { sock.end(JSON.stringify({ t: 'err', msg: 'table full' }) + '\n'); return; }
|
|
162
|
+
me = { id: nextId++, name: cleanName(m.name), sock, n: START_DICE, alive: false, dice: [] };
|
|
163
|
+
players.set(me.id, me);
|
|
164
|
+
if (hostId === null) hostId = me.id;
|
|
165
|
+
broadcast();
|
|
166
|
+
} else if (!me) {
|
|
167
|
+
continue;
|
|
168
|
+
} else if (m.t === 'start') {
|
|
169
|
+
if (phase === 'lobby' && me.id === hostId) {
|
|
170
|
+
if (players.size < 2) err('need at least 2 players'); else startGame();
|
|
171
|
+
}
|
|
172
|
+
} else if (m.t === 'bid' && phase === 'bidding' && turn === me.id) {
|
|
173
|
+
const { q, f } = m;
|
|
174
|
+
if (Number.isInteger(q) && Number.isInteger(f) && f >= 1 && f <= 6 && q >= 1 && q <= total() && validRaise(bid, q, f)) place(me, q, f);
|
|
175
|
+
else err('invalid bid: raise the quantity, or keep it and raise the face');
|
|
176
|
+
} else if (m.t === 'liar' && phase === 'bidding' && turn === me.id) {
|
|
177
|
+
if (bid) challenge(me); else err('nothing to challenge yet');
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
sock.on('close', () => { clearTimeout(joinTimer); if (me) leave(me); });
|
|
182
|
+
sock.on('error', () => sock.destroy());
|
|
183
|
+
};
|
|
184
|
+
const server = net.createServer(onConn);
|
|
185
|
+
server.listen(port, host);
|
|
186
|
+
return { server, attach: onConn, close() { clearTimeout(timer); for (const p of players.values()) p.sock.destroy(); server.close(); } };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = { createServer, validRaise, cleanName };
|