I am doing a project which consists of a multiplayer minigame with Node , Express and Socket.io in which each player has a different color that the server assigns to them when entering and the players will see a table which the players have to paint the cells and in the end whoever has painted the most cells wins.
My problem is that I assign the color red to the first player to enter, for example, the second to enter I assign green but now the player who was red is also green, if another player enters it will be blue but the rest of the players they will also be blue and so on.
How can I make each player have their own color and not update when another player enters? Thanks in advance.
Server
var id=1;
var colorhexadecimal;
io.on('connection', function(socket){
console.log("user"+id+" connected");
colorhexadecimal = "";
if(id==1){
colorhexadecimal = "orange";
}else if(id==2){
colorhexadecimal = "green";
}else if(id==3){
colorhexadecimal = "red";
}else if(id==4){
colorhexadecimal = "purple";
}else {
colorhexadecimal = "";
}
id++;
io.emit('colorEvent', colorhexadecimal);
socket.on('pintar', function(id){
io.emit('pintar', id);
});
socket.on('disconnect', function () {
console.log('A user disconnected');
});
Client
$(function () {
var socket = io();
socket.on('colorEvent', function(colorhexadecimal){
color = colorhexadecimal;
});
$('.celda').click(function(event){
var idRecibida = event.target.id;
socket.emit('pintar',idRecibida);
return false;
});
socket.on('pintar', function(id){
$('#'+id).css("background-color", color);
});
});
When you do a
io.emit()
what you do is notify all the connected clients, what you should do is send the emit only to the client that has just connected, not all of them change, theio.emit()
bysocket.emit()
, on the other hand if your colors are already defined, insert them in an array and just access the position of the array instead of using so many if's