Give each player a different color when they log in

1

I'm doing a project which consists of a multiplayer minigame with Node , Express and Socket.io in which each player has a different color assigned by the server when entering and players will see a table which players have to paint the cells and in the end who has painted more cells wins.

My problem is that the first player who enters assigned the red color for example, the second that comes in I assign the green but now the player who was red is also green, if another one comes in, it will be blue but the Other players will also be blue and so on.

How can I make each player color and not update when another player comes in? 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');
});

Customer

$(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);
  });

});    
    
asked by rafemo 16.04.2018 в 16:13
source

1 answer

0

When you make a io.emit() what you do is notify all the connected clients, what you should do is send the emitted only to the client that has just been connected not to all change, the io.emit() for socket.emit() , On the other hand, if your colors are already defined, insert them into an array and only access the array position instead of using so many if

var id=1;
const colors = ['','orange','green','red','purple'];

io.on('connection', function(socket){
  console.log("user"+id+" connected"); 
  if(id >=1 && id<= 4 ){
    colorhexadecimal = colors[id];
  } else {
    colorhexadecimal = colors[0];
  }
  id++;

  socket.emit('colorEvent', colorhexadecimal);

  socket.on('pintar', function(id){
   socket.emit('pintar', id);
  });

  socket.on('disconnect', function () {
   console.log('A user disconnected');
  });
});  
  
    
answered by 16.04.2018 / 16:31
source