im trying to convert this singleplayergame into a multiplayergame using websockets.
https://github.com/Loonride/slither.io-clone/tree/master/slither-io
so far, i've made a server, and a clientsocket so client A and client B can communicate to eachother their snakes X and Y positions in their respective consoles. so far, that works. but now im trying to draw a snake on those x,y positions and im having a bit of trouble with this because im not really sure where to even start on doing that. (im new to programming, and using this project to learn and get into coding).
here is what i have so far. in the server file (the part that handles the communication):
socket.on('snakeemit', snakeMsg);
function snakeMsg(snakehead) {
socket.broadcast.emit('snakeemit', snakehead);
console.log(snakehead);
}
}
and in the gamefile, in the "create:" section, i added this:
socket = io.connect('http://localhost:8080');
var snakehead = snake.head.position;
socket.emit('snakeemit', snakehead);
socket.on('snakeemit', newDrawing);
function newDrawing(snakehead){
console.log(snakehead);
}
so this seems to be working to get the client and server to communicate, and i can see the position of the head in my node.js console as well as in theclients console on google chrome.
to actually draw a snake on those coordinates, i have tried this, but it doesnt work. im not really sure where to go from here so if anyone want to get involved id be so happy!
function newDrawing(snakehead){
var snake = new PlayerSnake(this.game, 'circle', snakehead, snakehead);
}
Transfering only the head position is not enough to do anything useful with the data. Instead you would have to serialize the sections and their positions:
var username = "test"; // to be set on game start
function serializeSnake(snake) {
return {
username,
sections: snake.sections.map(section => ({ x: section.x, y: section.y })),
head: { x: snake.head.x, y: snake.head.y },
};
}
function deserializeSnake(data) {
const snake = new Snake(game, "circle", data.head.x, snake.data.y);
for(const section of data.sections)
snake.addSection(section.x, section.y);
}
Now you can easily transfer the snakes data every x seconds:
setInterval(function () {
socket.emit('snakeemit', serializeSnake(snake));
}, 2000);
When it arrives on another client, you can add the snake to the snakes:
const snakeByPlayer = new Map/*<string, Snake>*/();
socket.on("snakeemit", function(data) {
if(snakeByPlayer.has(data.username)) {
// update the snake with the data
} else {
const snake = deserializeSnake(data);
game.snakes.push(snake);
snakeByPlayer.set(snake.username, snake);
}
});