samedi 13 avril 2019

Better random number generator for Android

I'm working on an automated Rock paper scissors app in Android, where both "players" are assigned a value and then a winner is evaluated. This repeats once a second.

String[] options = {"rock", "paper", "scissors"};

final String selected_player1 = options[new Random().nextInt(options.length)];
final String selected_player2 = options[new Random().nextInt(options.length)];

switch (selected_player1)
{
    case "rock":
        if (selected_player2.equals("paper"))
        {
            win_player2();
        }
        else if (selected_player2.equals("scissors"))
        {
            win_player1();
        }
        break;

    case "paper":
        if (selected_player2.equals("scissors"))
        {
            win_player2();
        }
        else if (selected_player2.equals("rock"))
        {
            win_player1();
        }
        break;

    case "scissors":
        if (selected_player2.equals("rock"))
        {
            win_player2();
        }
        else if (selected_player2.equals("paper"))
        {
            win_player1();
        }
        break;
}

The problem is that player2 seems to almost always pick either the same option as player1 or the winning option, so after a minute (60 ticks) the score is always something like 1:20. If I declare and initialize player2 first, the score flips over.

Is it possible to use some different/better RNG algorithm to prevent this from happening? Or is there something wrong with my code?




Aucun commentaire:

Enregistrer un commentaire