import express from 'express' import cookieParser from 'cookie-parser' const app = express() app.use(cookieParser()) // ... // Returns the user's userid, creating a random // userid if there is none, storing it as a cookie. function getUserId(req, res) { let userid = req.cookies.userid if (userid == undefined) { userid = crypto.randomUUID() // random unique ID res.cookie('userid', userid) } return userid } // Create a copy of game to return and // sets the 'color' and 'yourturn' entries // according to the user id. function sendGame(req, res) { // Join a game that is waiting for players. let userid = getUserId(req, res) if (game.player_X == undefined) { // Join game as X console.log(`User ${userid} joining game as X`) game.player_X = userid } else if (game.player_O == undefined && game.player_X != userid) { // Join game as O console.log(`User ${userid} joining game as O`) game.player_O = userid } // Create a copy and set the 'color' property let copy = structuredClone(game) if (game.player_X == userid) { // User is already assigned X copy.color = 'X' } else if (game.player_O == userid) { // User is already assigned O copy.color = 'O' } else { // game already has two other players } // Set the 'yourturn' property if applicable if (copy.state.next == copy.color) { copy.yourturn = true } res.json(copy) } app.get('/game/', (req, res) => { sendGame(req, res); });