
// JumbleGame.java
// https://www.quickprogrammingtips.com/java/jumble-word-game-in-java.html
// Modified by Andrew Davison, ad@coe.psu.ac.th, Dec. 2022

/* A guess-the-word game, where the word is generated by getting Hunspell
   to suggest a dictionary word that 'corrects' a word made up of
   randomly generated letters.

   Two things of note: Hunspell can produce no suggestions if the random
   word is too strange, which prompted me to add an 'e' to the random
   letters. Secondly, the suggested word need not be the same length as 
   the random word (which is of length NUM_LETTERS).

  Usage:
    > compile JumbleGame.java
    > run JumbleGame
    e.g.
      Shuffled word is: eivfufla
      1/5. Make a guess: flavfuie
      - Nope
      2/5. Make a guess: effliav
      - Nope
      3/5. Make a guess: affvuiel
      - Nope
      4/5. Make a guess: fivefula
      - Nope
      5/5. Make a guess: laffiuve
      - Nope
      - Game Over. The word was: effluvia
*/


import java.util.*;


public class JumbleGame
{
  private static final int NUM_LETTERS = 6;
  private static final int MAX_TRIES = 5;

  private static Random rand = new Random();


  public static void main(String[] args)
  {
    HunspellChecker hsc = new HunspellChecker();

    String randWord = randomLetters(hsc);
    // System.out.println("Original word is: " + randWord);
    String shuffled = WordUtils.shuffle(randWord);
    System.out.println("Shuffled word is: " + shuffled);

    Scanner sn = new Scanner(System.in);
    int numTries = 0;
    while (numTries < MAX_TRIES) {
      numTries++;
      System.out.print(numTries + "/" + MAX_TRIES + ". Make a guess: ");
      String guess = sn.nextLine().trim();
      if(randWord.equalsIgnoreCase(guess)) {
        System.out.println("- Won in " + numTries + " guesses");
        break;
      }
      else
        System.out.println("- Nope");
    }

    if (numTries == MAX_TRIES)
      System.out.println("- Game Over. The word was: " + randWord);
    hsc.close();
  } // end of main()


  private static String randomLetters(HunspellChecker hsc)
  /* the infinite loop is a tad dangerous, but in practice
     Hunspell makes a suggestion after at most two loops.
  */
  {
    while (true) {
      char[] letters = new char[NUM_LETTERS];
      for (int i=0; i < NUM_LETTERS; i++)
        letters[i] = (char)(rand.nextInt(26)+'a');

      letters[rand.nextInt(NUM_LETTERS)] = 'e';
       // added to make the letters more likely to be a word

      String s = new String(letters);
      // System.out.println("string: " + s);
      String word = hsc.suggest(s);
      if (word != null)  // there is a suggestion
        return word;
    }
  }  // end of randomLetters()


}  // end of JumbleGame class

