From 9d201384db591cc94d872c4046a2bc67d1c57133 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Tue, 26 May 2020 21:13:49 -0700 Subject: [PATCH] tictactoe: Implement a minimally-functional multi-player game Now that there's a server implemented at lmno.games/tictactoe/LMNO/ it's a simple matter to break the call chain at handleClick() to not do any state updates, but instead hit the /move API, then wait for data to come back from the /events API and only when the server returns with that, _then_ to update the state. So, with multiple clients connected, each client will now seem the game state updated with each move. As far as the gameplay of Tic Tac Toe, the only major feature missing is that players are not yet restricted to play as either X or O but can instead send events for either player. Obviously, that won't be hard to fix. Then, as far as implementation, this code copies the add_message() function from lmno.js, so we'll want to find a better way to do that. And there may be some refactoring to be done for event handling as well, (to reduce code duplication between game implementations). But this code does use the fetch() API which does seem easier to use than XMLHttpRequest so that's something we will probably want to switch to in existing code. --- tictactoe/tictactoe.jsx | 59 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/tictactoe/tictactoe.jsx b/tictactoe/tictactoe.jsx index eff7eff..654d55e 100644 --- a/tictactoe/tictactoe.jsx +++ b/tictactoe/tictactoe.jsx @@ -1,3 +1,30 @@ +function undisplay(element) { + element.style.display="none"; +} + +function add_message(severity, message) { + message = `
+× +${message} +
`; + const message_area = document.getElementById('message-area'); + message_area.insertAdjacentHTML('beforeend', message); +} + +const events = new EventSource("events"); + +events.onerror = function(event) { + if (event.target.readyState === EventSource.CLOSED) { + add_message("danger", "Connection to server lost."); + } +}; + +events.addEventListener("move", event => { + const square = JSON.parse(event.data); + + window.game.receiveMove(square); +}); + function Square(props) { return (