vendredi 28 juillet 2017

Randomness and probability in java

I'm trying to make a small gambling game in Java where the user has two options.

A TextField where he can write in the amount of how much he wants to bet and a ComboBox where he can choose how many precent chance for him to win. The comboBox provides the options 10%, 20%, 30%, 40% and 50%.

My problem is that I don't know how to apply probability in java. I tried doing following:

public class GamblingGame {

private int rdmNumber;
private int wonValue;

public int winOrLose(int valueBetted, int precentToWin, Label label, int attempts){


    precentToWin = precentToWin/10;

    rdmNumber= ThreadLocalRandom.current().nextInt(precentToWin, 10 +1);


    System.out.println("this is rdmnumber: " + rdmNumber);
    System.out.println("this is precentowin number: " + precentToWin);

    //if the number you rolled is equal to the precent you choose (ie if its 10, the number is 1, if its 20 the number is 2)
    if(rdmNumber == precentToWin) {
        wonValue = valueBetted/precentToWin *2;

        System.out.println("You win!");

        label.setStyle("-fx-text-fill: green");
        label.setText("You won! You recieved: " + wonValue+" coins!");
    }

    else{
        label.setStyle("-fx-text-fill: red");
        label.setText("Gamble failed! You lost: " +valueBetted + " coins. ("+attempts+")");
        wonValue = -valueBetted;

    }


    System.out.println(wonValue);
    return wonValue;



}

}

The problem is that if, for instance, the user puts in 50% in the combobox he won't get a true 50% chance to win.

The number the dice would need to roll here is 5 in order to win, and the max value is 10. So the user would roll a number between 5-10 and when he hits 5, he'd win.

How do I make it so that the precentage of rolling the dice would be a true 50%? (and of course not ruin it so that if i put in a difference precentage as the parameter it wont ruin the method)




Aucun commentaire:

Enregistrer un commentaire