78 lines
1.8 KiB
JavaScript
78 lines
1.8 KiB
JavaScript
const {Board, Piece} = require('./src/backend');
|
|
|
|
const express = require("express");
|
|
const http = require("http");
|
|
const socketIo = require("socket.io");
|
|
|
|
const port = process.env.PORT || 4001;
|
|
|
|
const app = express();
|
|
|
|
const server = http.createServer(app);
|
|
|
|
const io = socketIo(server, {
|
|
cors: {
|
|
cors: true,
|
|
}
|
|
});
|
|
|
|
let interval;
|
|
|
|
let board = new Board();
|
|
|
|
let sockets = [];
|
|
let games = new Map();
|
|
|
|
io.on("connection", (socket) => {
|
|
sockets.push(socket);
|
|
console.log("New client connected");
|
|
if (interval) {
|
|
clearInterval(interval);
|
|
}
|
|
//interval = setInterval(() => getApiAndEmit(socket), 5000);
|
|
socket.on("disconnect", () => {
|
|
// TODO sockets.remove(socket)
|
|
console.log("Client disconnected");
|
|
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 = {
|
|
sockets: [socket],
|
|
board: new Board(),
|
|
moveDate: null,
|
|
};
|
|
console.log(`Created game '${key}'`);
|
|
}
|
|
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 (s of game.sockets) {
|
|
getApiAndEmit(s, game.board);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
const getApiAndEmit = (socket, board) => {
|
|
const response = board.textFromState();
|
|
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}`));
|