Generate a random profession for Online Players

5

I am creating a small game (Android) to play me some more friends of mine. The game is called "Cops and Thieves". At least it is necessary to have 4 players in which one of them will be the POLICE, another will be the CRIMINAL, another will be the DAMA and the rest will be CIVIS (Normal People).

I'm currently using Socket.IO to connect players and communicate. But at the time of giving a profession to each player, I came across a problem. This is the part of the code he creates and sends to the player his profession:

    var PoliceAlready,CriminalAlready,DamaAlready = false;
    for(var SI in clients) {
        var socket = clients[SI];
        var profissaoT;

        if(!PoliceAlready){
                profissaoT="POLÍCIA";
                PoliceAlready = true;
        }else if(!CriminalAlready){
                profissaoT="CRIMINOSO";
                CriminalAlready = true;
        }else if(!DamaAlready){
                profissaoT="DAMA";
                DamaAlready = true;
        }else{
                profissaoT="CIVÍL";
        }
        socket.emit('profissao', profissaoT);
 }

But it will have to have a Police, Criminal and Lady and these can not be repeated. From the code above it will do this, but the for () function will execute the data of the array "clients" in order, which means that it always has the same profession and the objective is always to re-execute this function give the profession, always be random!

var clients = {'/#53h2bn324buh234', '/#h32h324h5234uh2', '/#3pm3b4ij234'};

I would like to thank you for taking the time to help me, or at least to try.

    
asked by anonymous 23.12.2016 / 10:05

2 answers

5

The ideal would be to explain the shape I propose by drawing, but I will try to illustrate. To ensure that each player has a valid role and has only 1 Police Officer , 1 Lady and 1 Criminal p>

They take a box and put 5 papers written the professions available, such that after they finish the box will have 1 Police Officer , 1 Criminal , 1 Lady and 2 Cívis . They shake the box to shuffle and then each one takes out a piece of paper. In the end, each child will know their profession and there will be no risk of a police officer leaving or having two policemen.

What I did in this code is this. There is an array called roles, where they have numbers associated with professions, which are:

1 = Police Officer

2 = Criminal

3 = Lady

4 = Civil

If you have more than 4 players, the array is populated with civis, so push(4) . Then for each client a random profession is removed from the "box".

// deixar os papéis fixos
var papeis = [1, 2, 3, 4];

// Clientes em formato de array de objetos, para que cada cliente possua uma profissao
var clients = [{
  'id': '/#53h2bn324buh234',
  'profissao': null
}, {
  'id': '/#h32h324h5234uh2',
  'profissao': null
}, {
  'id': '/#3pm3b4ij234',
  'profissao': null
}, {
  'id': '/#3pm3b4ij222',
  'profissao': null
}];

// Se houver mais de 4 jogadores os demais serão civis
if (clients.length > 4) {
  for (var i = 0; i < clients.length - 4; i++) {
    papeis.push(4);
  }
}

// elegendo o papel para cada jogador
clients.forEach(function(cliente) {
  var aux = Math.floor(Math.random() * papeis.length);
  // splice remove o papel do array de papeis. Isso para
  // para que tenha somente 1 Policia, Dama e Criminoso.
  var papel = papeis.splice(aux, 1);
  cliente.profissao = obterProfissao(papel[0]);
  
  adicionarTela(cliente);
});

function adicionarTela(cliente) {
  var div = document.getElementById("papeis");
  var span = document.createElement("span");
  span.innerHTML = "<span> O jogador: " + cliente.id + " é: <b>" + cliente.profissao + "</b></span><br>"
  div.appendChild(span);
}

function obterProfissao(escolha) {
  //var socket = clients[SI];
  var profissaoT;

  if (escolha == 1) {
    profissaoT = "POLÍCIA";
    PoliceAlready = true;
  } else if (escolha == 2) {
    profissaoT = "CRIMINOSO";
    CriminalAlready = true;
  } else if (escolha == 3) {
    profissaoT = "DAMA";
    DamaAlready = true;
  } else {
    profissaoT = "CIVÍL";
  }
  return profissaoT;
  //socket.emit('profissao', profissaoT);
}
<div id="papeis">
</div>

PS: I loved this game!

    
23.12.2016 / 12:07
2

What you have to do is keep on the server side the professions that have already gone, in this case I will randomly choose one of the 3 main ones and then delete the chosen one, when some socket (player) leaves the game that prof provision.

This is a functional example of this functionality, although your client side is different you can test this in the browser. Since index.html and server.js are in the same folder.

server.js:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var jogadores = {}; // serve para guardar as sockets e respetiva profissões
var profs = ['POLÍCIA', 'CRIMINOSO', 'DAMA'];

app.get('/', function(req, res){
    res.sendfile('index.html'); // enviar ficheiro para o browser
});

io.on('connection', function(socket){
    socket.on('chose_prof', function () {
        if(!(socket.id in jogadores)) {
            var prof = 'CIVIL'; // civil por default
            if(profs.length > 0) { // se ainda existirem as profissões princípais
                prof = profs[Math.floor(Math.random()*profs.length)]; // escolher prof ao acaso
                profs.splice(profs.indexOf(prof), 1); // apagar prof sorteada do nosso array de profs
            }
            jogadores[socket.id] = prof; // guardar socket e prof no obj jogadores, fazer console.log(jogadores); para perceberes
            io.to(socket.id).emit('new_prof', {prof: prof}); // enviar profissão sorteada
        }
    });
    socket.on('disconnect', function() {
        if(socket.id in jogadores) {
            if(jogadores[socket.id] != 'CIVIL') {
                profs.push(jogadores[socket.id]); // profissão de quem saiu do jogo fica de novo à disposição para outros que entrem
            }
            delete jogadores[socket.id]; // apagar jogador do nosso obj
        }
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

index.html:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script><buttonid="gera_prof">Gerar Prof</button>
<script>
    const socket = io();
    const prof_btn = document.getElementById('gera_prof');
    prof_btn.addEventListener('click', function() { 
        socket.emit('chose_prof');
    });
    socket.on('new_prof', function(info){ // receber informação do servidor
        document.body.innerHTML += 'Tu és ' +info.prof;
    });
</script>

I mentioned what I think should be clarified, in case you doubt it.

    
23.12.2016 / 11:22