QuickChess/server.js

84 lines
2.0 KiB
JavaScript

import packageJSON from './package.json' with { type: "json" }
import { textFromBoard } from './src/logic.js'
import { Board } from './src/backend.js';
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
const port = process.env.PORT || 4001;
const app = express();
app.get('/status', (req, res) => {
res.send('OK. Version: ' + packageJSON.version + '\n')
})
const server = http.createServer(app);
const io = new Server(server, {
cors: {
cors: true,
}
});
let interval;
let games = new Map();
io.on("connection", (socket) => {
console.log("New client connected");
if (interval) {
clearInterval(interval);
}
//interval = setInterval(() => getApiAndEmit(socket), 5000);
socket.on("disconnect", () => {
const game = socket.connectedGame
const gameMessage = game ? `from game '${game.key}'` : "and was not attached to a game"
console.log("Client disconnected " + gameMessage);
clearInterval(interval);
});
socket.on("find", key => {
key = key?.toLowerCase()
console.log(`Finding game '${key}'`);
let game = games.get(key);
if(game) {
console.log(`Found game '${key}'`);
game.sockets.push(socket);
} else {
game = {
key,
sockets: [socket],
board: new Board(),
moveDate: null,
};
console.log(`Created game '${key}'`);
}
socket.connectedGame = game;
games.set(key, game);
getApiAndEmit(socket, game.board);
});
socket.on("move", (key, move) => {
console.log(`Received move at '${key}'`);
let game = games.get(key);
if(move && game.board.makeMove(move.from, move.to) === 0) {
games.set(key, game);
for (const s of game.sockets) {
getApiAndEmit(s, game.board);
}
}
});
});
const getApiAndEmit = (socket, board) => {
const response = textFromBoard(board)
console.log(response);
// Emitting a new message. Will be consumed by the client
socket.emit("FromAPI", response);
};
server.listen(port, () => console.log(`Listening on port ${port}`));