From 875e12b88f55250c4adb0a5304b150ac00ce4efd Mon Sep 17 00:00:00 2001 From: Tor Andersson Date: Sat, 5 Mar 2022 11:32:38 +0100 Subject: Add query/reply API to server and modules. --- public/common/play.js | 15 ++++++++++++++- server.js | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/public/common/play.js b/public/common/play.js index e58ca04..0fa432a 100644 --- a/public/common/play.js +++ b/public/common/play.js @@ -376,12 +376,18 @@ function connect_play() { case 'state': view = arg; on_update_header(); - on_update(); + if (typeof on_update === 'function') + on_update(); on_update_log(); if (view.game_over) on_game_over(); break; + case 'reply': + if (typeof on_reply === 'function') + on_reply(arg[0], arg[1]); + break; + case 'save': window.localStorage[params.title_id + "/save"] = arg; break; @@ -547,6 +553,13 @@ function send_action(verb, noun) { return false; } +function send_query(q, param) { + if (param !== undefined) + send_message("query", [q, param]); + else + send_message("query", q); +} + function confirm_resign() { if (window.confirm("Are you sure that you want to resign?")) send_message("resign"); diff --git a/server.js b/server.js index a8a97e1..f97a0ed 100644 --- a/server.js +++ b/server.js @@ -1624,11 +1624,34 @@ function on_action(socket, action, arg) { } } +function on_query(socket, q) { + let params = undefined; + if (Array.isArray(q)) { + params = q[1]; + q = q[0]; + } + if (params !== undefined) + SLOG(socket, "QUERY", q, JSON.stringify(params)); + else + SLOG(socket, "QUERY", q); + try { + if (socket.rules.query) { + let state = get_game_state(socket.game_id); + let reply = socket.rules.query(state, socket.role, q, params); + send_message(socket, 'reply', [q, reply]); + } + } catch (err) { + console.log(err); + return send_message(socket, 'error', err.toString()); + } +} + function on_resign(socket) { SLOG(socket, "RESIGN"); try { let state = get_game_state(socket.game_id); let old_active = state.active; + // TODO: shared "resign" function state = socket.rules.resign(state, socket.role); put_game_state(socket.game_id, state, old_active); put_replay(socket.game_id, socket.role, 'resign', null); @@ -1739,6 +1762,7 @@ function on_restart(socket, scenario) { function handle_message(socket, cmd, arg) { switch (cmd) { case 'action': on_action(socket, arg[0], arg[1]); break; + case 'query': on_query(socket, arg); break; case 'resign': on_resign(socket); break; case 'getchat': on_getchat(socket, arg); break; case 'chat': on_chat(socket, arg); break; -- cgit v1.2.3