Deciding who is player one and two in a round base

2020-04-04 04:08发布

问题:

I have a round-based Multiplayer game for Android that has been working over XMPP before, and I want to switch to Google Play Game Services. In the old version, there was an XMPP bot, deciding which player will be player 1 or 2. This is important to know which player should make the first move.

With Google Play Game Services, I found a solution that nearly works:

@Override
public void onRoomConnected(int statusCode, Room room) {
    ArrayList<Participant> participants = room.getParticipants();
    Participant first = participants.get(0);
    if (first.getPlayer() == null || !first.getPlayer().getPlayerId().equals(myPlayerId)) {
        LaskaField.HUMAN_PLAYER = 2;
        LaskaField.OTHER_PLAYER = 1;
        opponent = first.getDisplayName();
    } else {
        LaskaField.HUMAN_PLAYER = 1;
        LaskaField.OTHER_PLAYER = 2;
        opponent = participants.get(1).getDisplayName();
    }
    setPlayerNames();
}

This way works fine when inviting another player. However, it often fails when both players select auto-matching. In this case, both players are on the same position in the participants ArrayList. Therefore, they will both appear as the same player on their currently used device.

What is the right way to select player 1 and 2, with no central instance for deciding this. Is there any useful data in the participants list that I didn't find with the debugger?

回答1:

I have solved the problem by comparing the player ids (which are random for each game):

String myid = mActiveRoom.getParticipantId(client.getCurrentPlayerId());
String remoteId = null;

ArrayList<String> ids = mActiveRoom.getParticipantIds();
for(int i=0; i<ids.size(); i++)
{
    String test = ids.get(i);
    if( !test.equals(myid) )
    {
        remoteId = test;
        break;
    }
}

boolean iMakeTheFirstMove = ( myid.compareTo(remoteId) > 0 );


回答2:

This is a standard issue of selecting a leader from a bunch of unorganized nodes. There's some fairly advanced ways to do it, I'm sure. If you want to check out: Automatic selection of a leader in a cluster of nodes and hte Paxos algorithm.

Now...that being said, since you have a limit of 4 people, theres easier ways to do it. You could just treat their ID's as a number, and who ever has the highest ID is player 1, and descending in order. That would probably be the simplest way.

You could also have all the players submit a random roll and broad cast it. In the extremely rare case of a duplicate, you can have a reroll. Once everyone has made their rolls, and everyone has the same data, each individual client can determine the player order based on the value of the rolls.

I wouldn't do anything related to the order in the array however. I don't believe that's guaranteed in any circumstance.