MultiplayerMinesweeper/scripts/server/netcode.mjs

77 lines
2.3 KiB
JavaScript

import {IllegalAction} from "./illegalAction.mjs"
import * as log from "../log.mjs"
import {roomManager} from "../roomManager.mjs"
import {io} from "./io.mjs"
io.on('connection', function(client){
connected(client)
});
function connected(client) {
client.sync = function() {
const tempWorld = client.game.world.obfuscate();
io.to(client.game.id).emit('sync',{world: tempWorld})
}
client.sendMeta = function() {
const roomID = client.game.id
const roomPlayers = client.game.players; // Dont send client id's to everyone, TODO
const metadata = {players: roomPlayers, roomID: roomID}
io.to(client.game.id).emit('metadata', metadata)
const id = client.game.id
client.emit('message', id)
}
client.game = "";
client.player = "";
client.on('disconnect', function(){
if (!roomManager.getAllPlayerIDs().includes(client.id)) return new IllegalAction(client.id, 22)
log.log(client.id + ' disconnected.', 'FgCyan')
client.game.removePlayerByID(client.id)
client.sendMeta();
})
client.on('joinGame', function(data){
const info = roomManager.playerJoinGame(data.room, data.name, client.id)
client.join(info[0].id)
client.game = info[0];
client.player = info[1]
client.sync()
log.log(`${client.id} joined the game as ${data.name} requesting to join room: ${data.room}`, 'FgMagenta');
client.emit('inGame', true)
client.sendMeta()
})
client.on('createGame', function(data){
const info = roomManager.playerCreateGame(data.options, data.name, client.id)
client.join(info[0].id)
client.game = info[0];
client.player = info[1]
log.log(`${client.id} joined the game as ${data.name} `, 'FgMagenta');
client.emit('inGame', true)
client.sync()
client.sendMeta()
})
client.on('leaveGame', function(data){
log.log(client.id + ' disconnected.')
client.game.removePlayerByID(client.id)
})
client.on('clickCanvas', function(data){
if (!roomManager.getAllPlayerIDs().includes(client.id)) return new IllegalAction(client.id, 1)
client.game.world.click(data.tilePosition[0],data.tilePosition[1], data.mode, client.player)
client.sync()
})
}