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
|
#!/usr/bin/env node
const net = require("net");
const util = require("util");
const protocol = require("./protocol.js");
const keyboard = require("./keyboard.js");
if (process.argv.length != 4) {
console.log("Usage: ./client.js <hostname> <port>");
console.log("Pass address of doomrooms server as arguments.");
process.exit(1);
}
const GAME_ID = "tictactoe-tom";
keyboard.init();
function fatalError(err) {
console.log("A fatal error occurred:");
console.log(" ", err);
process.exit(1);
}
function showMenu(title, options) {
return new Promise(async (resolve, reject) => {
console.log(title);
for (let i = 0; i < options.length; i++) {
console.log(" " + (i + 1) + ") " + options[i]);
}
while (true) {
const line = await keyboard.prompt("> ");
const num = parseInt(line.trim(), 10);
if (num >= 1 && num <= options.length) {
resolve(num - 1);
break;
}
console.log(
"That's an invalid choice. " +
"Please enter a number between 1 and " + options.length + ".");
}
});
}
function messageHandler(msg) {
console.log("Message: " + util.inspect(msg));
}
const conn = new protocol.Connection(net.createConnection(+process.argv[3], process.argv[2]), messageHandler);
conn.conn.on("connect", async () => {
console.log("Connected to Doomrooms.");
let choice = await showMenu("Register or log in?", ["Register new account", "Log in to existing account"])
const username = await keyboard.prompt("Username: ");
const password = await keyboard.prompt("Password: ");
let msg;
if (choice == 0) {
msg = await conn.send(new protocol.Message("make-player", username, password));
} else {
msg = await conn.send(new protocol.Message("login", username, password));
}
if (msg.err) fatalError(msg.err);
console.log(msg);
msg = await conn.send(new protocol.Message("set-game", GAME_ID));
if (msg.err) fatalError(msg.err);
setTimeout(() => {process.exit(0);}, 2000);
});
|