dimanche 11 mars 2018

Number guessing game in JavaFX

I'm currently stuck on a simple program which has a Guess and Reset button for guess a number from 1-100. The user is given 5 turns. My current issue is that I can't get my Reset button to correctly function. When it is pressed, rather than generating a new game entirely, it instead just generates a new number but when Guess is then pressed the original number that was generated is used again.

I'll include some code snippets where I feel I am making big logic errors.

So just my counter and initial random number variables and then the Guess and Reset button

       int counter = 0;
       int num = genRan();

   /////////////////////////////////////
        guessButton.setOnAction(e -> {

        int numToGuess = num;

        gameSetUp(guessField, counter, numToGuess);

    });

    //////////////////////////////////////////////////////////

    resetButton.setOnAction(e -> {

        System.out.println("Generating new game...");

        int newNum = genRan();
        int newCounter = 0;

        gameSetUp(guessField, newCounter, newNum);

    });

My random number generator.

public int genRan() {
        Random rand = new Random();

        int numToGuess = rand.nextInt(100) + 1;

        System.out.println("number is" + numToGuess);

        return numToGuess;
    }

And where I think it's all going wrong...

public void gameSetUp(TextField guessField, int counter, int num) {

    int numToGuess = num, maxGuesses = 5;

    try {
        if (counter != 5) {
            int guessNum = Integer.valueOf(guessField.getText());

            if (guessNum == numToGuess) {
                System.out.println("Correct!");
            } else if (guessNum < numToGuess) {
                counter++;
                System.out.println("You guessed " + guessNum + ", which was too low. " + (maxGuesses - counter)
                        + " guesses left!");
            } else if (guessNum > numToGuess) {
                counter++;
                System.out.println("You guessed " + guessNum + ", which was too high. " + (maxGuesses - counter)
                        + " guesses left!");
            }
        }

    } finally {
        if (counter == maxGuesses) {
            System.out.println("\nGame Over...");
        }
    }
}

I'd appreciate any help at all, thanks.




Aucun commentaire:

Enregistrer un commentaire