import java.util.Random; import java.util.Scanner; /** * Simple example game with a (volatile) highscore table. */ public class HiLoGame { /** * Array to store highscore information. * highscore[0] = top score * highscore[9] = lowest highscore */ private static int[] highscore = new int[10]; /** * Runs through the array in a for loop and prints the scores. * The top score should be printed first. */ public static void showHighscore() { System.out.println("*** HIGHSCORE ***"); for (int i=0; i<10; ++i) System.out.println(highscore[i]); } /** * Enters a new score into the highscore array. * The order must be maintained and no lower score should ever replace a higher one. */ public static void insertScore(int score) { if (score > highscore[9]) { // good enough for a highscore? int pos = 0; while (score < highscore[pos] && pos < 10) ++pos; for (int i=8; i>=pos; --i) highscore[i+1] = highscore[i]; highscore[pos] = score; } } /** * Should show a valid highscore table. * Especially the values must always appear in descending order. */ public static void testScore() { for (int i=0; i<100; i+=10) insertScore(i); insertScore(55); showHighscore(); insertScore(15); showHighscore(); insertScore(95); showHighscore(); insertScore(5); showHighscore(); } /** * The game. */ public static void main(String[] args) { boolean done = false; Random rand = new Random(); Scanner sc= new Scanner(System.in); System.out.println("Welcome to HiLo, I've got a secret number between 0 and 99 ..."); while (!done) { int step = 0; int secret = rand.nextInt(100); int guess = 0; do { System.out.print("Guess: "); guess = sc.nextInt(); if (guess < secret) System.out.println("too low, guess higher"); if (guess > secret) System.out.println("too high, guess lower"); ++step; } while (secret != guess); int score = (31 - step) * 7 + rand.nextInt(7); if (score < 0) score = 0; System.out.println("Congratulation, your score is: "+score); insertScore(score); showHighscore(); System.out.println("Play again? (Yes/No) "); String str = sc.next(); done = str.contains("N") || str.contains("n"); } System.out.println("Bye bye"); } }