1
0

New game launching works!

Signed-off-by: James Ketrenos <james_git@ketrenos.com>
This commit is contained in:
James Ketr 2022-01-28 18:27:13 -08:00
parent 7f813ff2bd
commit ddfefef8b1

View File

@ -144,14 +144,14 @@ const loadGame = async (id) => {
}); });
if (!game) { if (!game) {
return undefined; games[id] = createGame(id);
} } else {
try {
try { games[id] = JSON.parse(game);
games[id] = JSON.parse(game); } catch (error) {
} catch (error) { console.error(error, game);
console.error(error, game); return null;
return null; }
} }
return games[id]; return games[id];
@ -351,20 +351,16 @@ router.put("/:id/:action/:value?", async (req, res) => {
router.get("/:id", async (req, res/*, next*/) => { router.get("/:id", async (req, res/*, next*/) => {
const { id } = req.params; const { id } = req.params;
console.log("GET games/" + id); console.log("GET games/" + id);
let error;
const game = await loadGame(id); let game = await loadGame(id);
if (game) { if (game) {
return sendGame(res, req, game) return sendGame(res, req, game)
} }
error = `Game ${id} not found -- returning invalid game state.`; game = createGame(id);
const invalid = { req.session.playerColor = null;
id: id,
players: {}, return sendGame(res, req, game);
state: 'invalid'
};
return sendGame(res, req, invalid, error);
}); });
router.put("/:id", (req, res/*, next*/) => { router.put("/:id", (req, res/*, next*/) => {
@ -435,15 +431,8 @@ const sendGame = async (res, req, game, error) => {
return res.status(200).send(playerGame); return res.status(200).send(playerGame);
} }
router.post("/:id?", (req, res/*, next*/) => { const createGame = (id) => {
console.log("POST games/"); id = id ? id : crypto.randomBytes(8).toString('hex');
const { id } = req.params;
if (id && id in games) {
const error = `Can not create new game for ${id} -- it already exists.`
console.error(error);
return res.status(400).send(error);
}
const game = { const game = {
startTime: Date.now(), startTime: Date.now(),
turns: 0, turns: 0,
@ -467,14 +456,27 @@ router.post("/:id?", (req, res/*, next*/) => {
wheat: 19, wheat: 19,
longestRoad: null, longestRoad: null,
largestArmy: null, largestArmy: null,
chat: [ { from: "R", date: Date.now(), message: "Server initialized!" } ], chat: [ { date: Date.now(), message: `New game started for ${id}` } ],
id: id ? id : crypto.randomBytes(8).toString('hex') id: id
}; };
games[game.id] = game; games[game.id] = game;
req.session.playerColor = null;
shuffleBoard(game); shuffleBoard(game);
console.log(`New game created: ${game.id}`); console.log(`New game created: ${game.id}`);
return game;
};
router.post("/:id?", (req, res/*, next*/) => {
console.log("POST games/");
const { id } = req.params;
if (id && id in games) {
const error = `Can not create new game for ${id} -- it already exists.`
console.error(error);
return res.status(400).send(error);
}
const game = createGame(id);
req.session.playerColor = null;
return sendGame(res, req, game); return sendGame(res, req, game);
}); });