Generate a random profession for Online Players

Asked

Viewed 939 times

5

I am creating a small game (Android) to play I 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 LADY and the rest will be CIVIL (Normal People).

I am currently using Socket.IO to make the connection between players and communication. But when it came to giving each player a profession, I ran into a problem. This is the part of the code in which 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 you must have a police officer, a criminal and a lady, and they must never happen again. Apart from the above code it will do just that, but the function for() will execute the data of the array "clients" in order, which makes it always have the same profession and the goal is to always return to perform this function of giving the profession, always be randomly!

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

I would like to thank those who are willing to help me, or at least try.

2 answers

5


The ideal would be to explain the way I propose drawing, but I will try to illustrate. To ensure that each player will have a valid role and has only 1 Policeman, 1 Lady and 1 Criminal Let’s imagine 5 children playing.

They take a box and put 5 papers written the available professions, such that after they finish the box will have 1 Policeman, 1 Criminal, 1 Lady and 2 Cyvis. They shake the box to shuffle and then each takes a piece of paper. In the end, every child will know his profession and there will be no risk of no policeman leaving or having two policemen.

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

1 = Policeman

2 = Criminal

3 = Lady

4 = Vil

If you have more than 4 players, the array is filled with cyvils, so the push(4). Then for each client is removed a profession randomly 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 that game!

  • 1

    Lucas, I may have misunderstood the question and the game, but I think I also played this game :P . But so to someone who gets to know the teachers of all, right? Shouldn’t each one just know his own? Anyway +1

  • In real life yes @Miguel! You say this because you feel that the professions should be allocated on the server?

  • Yes, at least I thought I did. So that there will be no conflicts and each one only know his... Very soon we see

  • You’re right. It actually displays in HTML only to make the distribution of the papers visible. And I did in javascript to show the logic :) in case just pass to Node, or PHP to be more suitable.

  • 1

    It worked Lucas, I did the respective tests and it’s exactly as I wanted!

  • http://image.prntscr.com/image/74c41261bcb64f92bf2e1aa2862ddcec.png

  • Nice guy! I’m happy to help :)

  • Miguel, the chosen profession will be sent only to that same player with a Socket Emit. The game I am creating is based on Sockets (Socket.IO,Nodejs,...) with an Android application (Java)!

Show 3 more comments

2

What you have to do is to save on the server side the professions that have already left, in this case I choose at random one of the 3 principles and then delete the chosen one, when some socket (player) leaves the game that prof is again available.

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>
<button id="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 commented on what I think should be clarified, in case you have doubts says.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.