import express from 'express' import cookieParser from 'cookie-parser' import { newGame, dropPiece, toJson, isWaiting, joinGame } from './connect4.js' const app = express() app.use(cookieParser()) const port = 3001 /** Retrieve the user's identifier from the cookies, or set a new one. */ function getUserId(req, res) { let userid = req.cookies.userid if (userid == undefined) { userid = crypto.randomUUID() res.cookie('userid', userid) } return userid } /* The empty path will join a waiting game or create a fresh one. * Afterwards, the request is redirected to /:gameid/. */ app.get('', (req, res) => { const userid = getUserId(req, res) // First attempt to find a waiting game and join that. for (let game of Object.values(games)) { if (isWaiting(game, userid)) { joinGame(game, userid) console.log(`Game ${game.id} randomly joined by ${userid}`) res.redirect(`${game.id}/`) return } } // No waiting game found - create a new one let game = newGame(nextGameId) games[nextGameId] = game nextGameId += 1 joinGame(game, userid) console.log(`Game ${game.id} started by ${userid}`) res.redirect(`${game.id}/`) })