Search code examples
google-play-games

How to decide who is the first player when user plays quick game?


I am using following code in onRoomConnected(int statusCode, Room room) for deciding who is the first player. But some times I am getting first/second for both players same. How to resolve this error.

        if (quickGame) {
            myTurn = room.getParticipants().get(0).getParticipantId().equals(myId);
        } else {
            myTurn = room.getCreatorId().equals(myId);
        }
        if (myTurn) {
            Log.e(TAG, "First Player");
            status.setText("Click a button to start");
        } else {
            Log.e(TAG, "Second Player");
            status.setText("Wait for opponent to start");
        }

Solution

  • The set of participant IDs is guaranteed to be the same to everybody who is in the room (but not across different matches). However, their order in the list is not guaranteed. So if you want to make an easy election (e.g. establish who goes first, etc), you must rely on the set of participant IDs, but not in the order. Some of the ways you can accomplish this are:

    1. The participant ID that comes alphabetically first is the first player to play
    2. The participant ID that comes alphabetically first is responsible for randomly electing a player to start first. The other clients will wait until that participants sends a reliable real time message containing the ID of the elected participant.

    Method (2) is preferred, because it doesn't contain a possible bias.

    Why? Although we don't specify what's the structure of a participant ID (it's just a string), the truth is that it does encode information, so if you use the participant ID as a rule, you might end up with a weird distribution of who goes first. For example, you might find that a particular player is always going first, but that's because, coincidentally, their participant ID is generated in such a way that this always happens. So it's definitely a better idea to use the participant ID to elect who is the authority to randomly decide who goes first, not who actually goes first.