diff options
Diffstat (limited to 'client.js')
-rwxr-xr-x | client.js | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/client.js b/client.js new file mode 100755 index 0000000..9493789 --- /dev/null +++ b/client.js @@ -0,0 +1,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); +}); |