MultiplayerMinesweeper/scripts/server/netcode.mjs

56 lines
1.8 KiB
JavaScript

import {IllegalAction} from "./illegalAction.mjs"
import * as log from "../log.mjs"
import {roomManager} from "../roomManager.mjs"
import {io} from "./io.mjs"
var oldWorld = 0
io.on('connection', function(client){
connected(client)
});
function connected(client) {
client.sync = function() {
const tempWorld = client.game.world.obfuscate();
io.to(client.game.name).emit('sync',{world: tempWorld})
}
client.sendMeta = function() {
const roomSettings = client.game.getSettings();
const roomPlayers = client.game.players; // Dont send client id's to everyone, TODO
const metadata = {players: roomPlayers, settings: roomSettings}
io.to(client.game.name).emit('metadata', metadata)
}
client.game = "";
client.player = "";
client.on('disconnect', function(){
if (!roomManager.getAllIDs().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){
if(!roomManager.joinClientToGame(data.room, data.name, client.id, client)) return
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('leaveGame', function(data){
log.log(client.id + ' disconnected.')
client.game.removePlayerByID(client.id)
})
client.on('clickCanvas', function(data){
if (!roomManager.getAllIDs().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()
})
}