Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * File: Hangman.java
- * ------------------
- * This program will eventually play the Hangman game from
- * Assignment #4.
- */
- import acm.graphics.*;
- import acm.program.*;
- import acm.util.*;
- import java.awt.*;
- public class Hangman extends ConsoleProgram {
- private RandomGenerator rgen = RandomGenerator.getInstance();
- HangmanLexicon lexicon = new HangmanLexicon();
- private int numberOfGuesses = 8;
- private String result;
- private String word;
- public void run() {
- println("Welcome to Hangman!");
- generateRandomWord();
- }
- private void generateRandomWord() {
- int random = rgen.nextInt(0, lexicon.getWordCount() - 1);
- word = lexicon.getWord(random);
- println(word);
- result = "";
- int length = word.length();
- for(int i = 0; i < length; i++) {
- result = result + "-";
- }
- println("The word now looks like this: " + result);
- println("You have " + numberOfGuesses + " guesses left." );
- guessWords(length);
- }
- private void guessWords(int length) {
- while (true) {
- int counterWin = 0;
- int counterLoss = 0;
- if (! result.equalsIgnoreCase(word) && numberOfGuesses > 0) {
- String input = readLine("Your guess: ");
- for (int i = 0; i < length; i++) {
- String currentLetter = word.substring(i, i + 1);
- int charIndex = word.indexOf(currentLetter);
- if (currentLetter.equalsIgnoreCase(input)) {
- counterWin = i;
- displayGoodMessage(counterWin, charIndex);
- println("That guess is correct.");
- if (result.equalsIgnoreCase(word)) {
- println("You guessed the word: " + word);
- println("You win.");
- } else {
- println("The word now looks like this: " + result);
- println("You have " + numberOfGuesses + " guesses left.");
- }
- } else {
- counterLoss++;
- }
- if (counterLoss == word.length()) {
- numberOfGuesses--;
- println("There are no " + input.toUpperCase() + "'s in the word.");
- if (numberOfGuesses == 0) {
- println("You're completely hung.");
- println("The word was: " + word);
- println("You lose.");
- } else {
- println("The word now looks like this: " + result);
- println("You have " + numberOfGuesses + " guesses left.");
- }
- }
- }
- }
- }
- }
- private String displayGoodMessage(int counterWin, int charIndex) {
- char letterCorrect = word.charAt(counterWin);
- for (int i = 0; i < word.length(); i++) {
- if (i == charIndex) {
- result = result.substring(0, i) + letterCorrect + result.substring(i + 1, word.length());
- }
- }
- return result;
- }
- }
Add Comment
Please, Sign In to add comment