Parcourir la source

(feat) Take user input for 6.5 number guessing game

It's quite fun actually!
main
Rob Hallam il y a 1 an
Parent
révision
89ece3f1b9
1 fichiers modifiés avec 21 ajouts et 12 suppressions
  1. +21
    -12
      week1.java

+ 21
- 12
week1.java Voir le fichier

@@ -456,36 +456,35 @@ class Lab6 extends Lab {

public six5() {
super(5);
System.out.println(String.format("TODO: get stdin working to user can play"));
numberGuessingGame();
// System.out.println(String.format("Testing randomBetween..."));
// int max = 100;
// int min = 50;
// for (int i=0; i<125; i++) {
// System.out.printf("%d ", randomBetween(min, max));
// }
// System.out.println(String.format("done."));
}

public void numberGuessingGame() {
final boolean SUPER_ADVANCED_AI = true;
final boolean SUPER_ADVANCED_AI = false; // true - simulated guesses, false - stdin
final Scanner userInput = new Scanner(System.in);
final int HIGHEST = 99;
final int MAX_GUESSES = 10;
int guess;

int chosenNumber = random.nextInt(HIGHEST+1);
int guess = random.nextInt(HIGHEST+1);
int chosenNumber = random.nextInt(HIGHEST + 1);
// super advanced AI section
int maxPossible = HIGHEST+1;
int maxPossible = HIGHEST + 1;
int minPossible = 0;

String guesses = "guess"; // for correct plurals

if (SUPER_ADVANCED_AI) {
guess = random.nextInt(HIGHEST+1);
} else {
guess = getUserGuess(userInput);
}
System.out.printf("Guessing...\t");
for (int i = 0; i < MAX_GUESSES; i++ ) {
System.out.printf("%d", guess);
if (guess == chosenNumber) {
System.out.println(String.format("\nYou guessed right after %d %s! It was indeed %d",
i+1, guesses, chosenNumber));
userInput.close();
return;
}
guesses = "guesses"; // didn't get it on the first try
@@ -503,11 +502,14 @@ class Lab6 extends Lab {
// but that's kinda boring and robotic
if (SUPER_ADVANCED_AI) {
guess = randomBetween(minPossible, maxPossible);
} else {
guess = getUserGuess(userInput);
}
// TODO change the behaviour so it doesn't guess the same number in a row
}

System.out.println(String.format("\nThe answer was: %d. Better luck next time!", chosenNumber));
userInput.close();

}

@@ -517,6 +519,13 @@ class Lab6 extends Lab {
// System.out.printf(" random.nextInt(%d - %d) + %d ", max, min, min);
return (random.nextInt(max - min) + min);
}

public int getUserGuess(Scanner userInput) {
System.out.println(String.format("Please enter an integer between 0 and 99 to guess"));
int guess = userInput.nextInt();
userInput.nextLine();
return guess;
}
}
/**
* Produce a number triangle


Chargement…
Annuler
Enregistrer