Skip to main content
Code Review

Return to Revisions

11 of 11
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/

Hangman game in Java - second try

Please look over my new object-oriented version of my Hangman game I posted here about two weeks ago.

I know I should work more on commenting and be clearer and more descriptive of the methods and their parameters and returns.

Menu class

public class Menu {
 public static void main(String[] args) {
 
 //Loop that will run until user chooses an input that causes exit
 while(true) {
 System.out.println();
 Menu menu = new Menu();
 menu.menuChoice(menu.menuSelect());
 }
 }
 
 // Prints out menu and calls method in UserInput class to get user input for menuselection
 public int menuSelect() {
 UserInput userInput = new UserInput();
 System.out.println("What do you want to do? \n1.Play Hangman\n2.Add a word to the word file\n3.List all the words in the list\n4.Exit");
 return userInput.inputMenuChoice();
 }
 
 /**
 *Selects the menu option with the Integer
 *
 *@param option -integer value that selects where to go with switch statement, -from menuSelect method
 */
 public void menuChoice(int option){
 
 FileHandling filehandling = new FileHandling();
 UserInput userInput = new UserInput();
 Word word = new Word();
 Game game = new Game();
 
 //Selects where to go
 switch(option) {
 case 1: 
 game.gameLoop();
 break;
 case 2: 
 filehandling.writeToFile(userInput.wordToWrite());
 break;
 case 3: 
 word.wordList(filehandling.readFile());
 break;
 case 4: 
 System.exit(0);
 break;
 default:
 System.exit(0);
 break;
 
 }
 } 
}

Board Class

public class Board {
 
 //Hangman Board - two dimensional array
 static char[][] board = {
 {'_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_'},
 {'_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '|'},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
 {'|', '_', '|', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_'},
 };
 
 /**
 *Writes to board depending on number of wrong inputs
 *
 *@param mistakes -number of wrong inputs - from game class
 */
 public void writeToBoard(int mistakes) {
 switch(mistakes) 
 {
 case 1: 
 board[4][11] = '0';
 break;
 case 2:
 board[5][11] = '|';
 break;
 case 3: 
 board[6][11] = '|';
 break;
 case 4: 
 board[7][11] = '|';
 break;
 case 5: 
 board[6][12] = '\\';
 break;
 case 6: 
 board[6][10] = '/';
 break;
 case 7: 
 board[8][11] = '\\';
 break;
 case 8: 
 board[8][9] = '/';
 System.out.println("You have lost!");
 break;
 default: break;
 
 } 
 }
 
 /**
 *Prints out the board along with used words and used characters in the game
 *
 *@param hangmanWordDisplay[] -char array from game class that displays the number of _ and characters found
 *@param usedCharacters[] -char array filled with used characters guessed by the user, correct and incorrect ones
 *@param usedWords[] - String array filled with used words guessed by the user, all incorrect
 */
 public void printBoard(char[] hangmanWordDisplay, char[] usedCharacters, String[] usedWords) {
 // Prints board
 for(char[] c : board) 
 {
 for(char elem : c) 
 {
 System.out.print(elem);
 }
 System.out.println();
 }
 
 //Prints out used characters
 System.out.print("\nUsed Characters: ");
 for(char c : usedCharacters) {
 System.out.print(c + "|");
 }
 //Prints out used words
 System.out.print("\nUsed words: ");
 for(String words : usedWords) {
 if(words == null) {
 System.out.print(" ");
 }else {
 System.out.print(words+ "|");
 }
 }
 
 // Prints hangmanwordDisplay array
 System.out.println();
 for(int i = 0; i < hangmanWordDisplay.length; i++) {
 System.out.print(hangmanWordDisplay[i]);
 } 
 System.out.print("\n");
 }
}

Word Class

public class Word {
 
 /**
 *Selects a word for the hangman game
 *
 *@param words[] -array of all the words read from the word file
 *@return - returns random word from the word array to be used in the game.
 */
 public String selectWord(String[] words) {
 return words[randWord(words.length)];
 }
 
 //Math function returning a random number
 public int randWord(int length) {
 return (int)(Math.random() * length);
 }
 
 // Returns true if the character entered by the user is equal to the character sent from the word in the game class
 public boolean testCharacter(char testChar, char charFromWord) {
 //Calls method to check if the characters are equal ignoring the case
 if(equalsIgnoreCase(testChar, charFromWord)) {
 return true;
 }
 return false;
 
 }
 
 // Method that uses .toLowerCase to make sure the if test ignores the case of the characters
 public boolean equalsIgnoreCase(char testChar, char charFromWord) {
 if(Character.toLowerCase(testChar) == Character.toLowerCase(charFromWord)) {
 return true;
 }
 return false;
 }
 
 //Checks if the word the user entered is equal to the word selected as the hangman word
 public boolean testWord(String testWord, String hangmanWord) {
 if(testWord.equalsIgnoreCase(hangmanWord)) {
 return true;
 }
 return false;
 }
 
 // Checks the userinput agains previously used characters found in the usedChar array
 public boolean hasUsedChar(char[] usedChar, char testChar) {
 //Iterates through the array
 for(char c : usedChar) {
 if(c == testChar) {
 return true;
 }
 }
 return false;
 }
 
 //Checks if the word entered had been a previously used word found in the usedWords array
 public boolean hasUsedWord(String[] usedWords, String word) {
 //Iterates through the usedWords array
 for(String Word : usedWords) {
 if(Word == null) { //avoids null pointer exception by telling ignore the rest of the code if the array element is empty
 continue;
 }
 if(Word.equalsIgnoreCase(word)) {
 return true;
 }
 }
 return false;
 }
 
 // Prints out all the words found in the word array
 public void wordList(String[] words) {
 for(String word : words) {
 System.out.println(word);
 }
 }
}

UserInput Class

import java.util.Scanner;
import java.util.InputMismatchException;
public class UserInput {
 private Scanner input = new Scanner(System.in);
 
 // Gets the Integer input for the menu class to select menu option
 public int inputMenuChoice() {
 int option = 0;
 try {
 option = input.nextInt();
 }catch(InputMismatchException e) {
 e.printStackTrace();
 }
 
 return option;
 }
 
 // Gets input for the hangman game for the game class
 public String gameInput() {
 System.out.print("Enter next character or attempt the full word: ");
 String userInput;
 
 try {
 userInput = input.nextLine();
 return userInput;
 }catch(InputMismatchException e) {
 e.printStackTrace();
 gameInput();
 }
 return null; 
 }
 
 // Gets a word from the user that's written to the word file
 public String wordToWrite() {
 System.out.println("Enter the word you wish to use");
 String userInput;
 
 try {
 userInput = input.nextLine();
 return userInput;
 }catch(InputMismatchException e) {
 e.printStackTrace();
 wordToWrite();
 }
 return null;
 }
}

FileHandling Class

import java.io.FileWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.IOException;
public class FileHandling {
 private File file = new File("word.txt");
 Scanner fileRead;
 public String[] wordArray;
 
 /**Constructor for FileHandling class
 *Checks if the file 'word.txt' already exists and creates it if it doesnt 
 */
 public FileHandling() {
 if(!file.exists()) {
 try {
 file.createNewFile();
 FileWriter writer = new FileWriter(file, true);
 fileRead = new Scanner(file);
 try {
 writer.write("Sindre\n");
 writer.write("Schmidt\n");
 }finally {
 writer.close();
 }
 }catch(IOException e) {
 e.printStackTrace();
 }
 }
 }
 
 /**
 *Reads all the lines from 'words.txt' in to a string array
 *@returns a string array to the game class 
 */
 public String[] readFile() {
 Scanner input;
 
 wordArray = new String[fileLength()];
 int count = 0;
 try {
 input = new Scanner(file);
 
 while(input.hasNextLine()) {
 wordArray[count] = input.nextLine();
 count++;
 }
 }catch(FileNotFoundException e) {
 e.printStackTrace();
 }
 
 return wordArray;
 }
 
 /**
 *Writes to the file 'words.txt' 
 *
 *@param word -Word from UserInput class
 */
 public void writeToFile(String word) {
 try {
 FileWriter writer = new FileWriter(file, true); 
 try {
 performWriteToFile(writer, word); // calls a method to write to file to make it cleaner
 }finally {
 writer.close();
 }
 }catch(IOException e) {
 
 }
 
 
 }
 // Writes word to file
 public void performWriteToFile(FileWriter writer, String word) throws IOException {
 writer.write(word + "\n");
 }
 
 // Checks the length of the file, uses that information to determine array size of the word array
 public int fileLength() {
 Scanner fileRead;
 int lines = 0;
 
 try{
 fileRead = new Scanner(file);
 
 //Iterates through the lines while there is a another one
 while(fileRead.hasNextLine()) { 
 lines++;
 fileRead.nextLine();
 }
 
 }catch(FileNotFoundException e) {
 e.printStackTrace();
 }
 
 return lines; // returns the number of lines
 }
}

Game Class

public class Game {
 private boolean running = true;
 private String hangmanWord;
 private char[] hangmanWordDisplay;
 private Word word = new Word();
 private char[] usedCharacters = new char[27];
 private String[] usedWords = new String[7];
 private String[] allWords;
 private int misses = 0;
 private boolean win = false;
 /**
 *Game class constructor that gets the hangman word, calls the method to read the 'word.txt file' 
 *and sets hangmanWordDisplay variable
 */
 public Game(){
 FileHandling filehandling = new FileHandling();
 allWords = filehandling.readFile();
 hangmanWord = word.selectWord(allWords);
 hangmanWordDisplay = new char[hangmanWord.length()];
 for(int i = 0; i < hangmanWord.length(); i++) {
 hangmanWordDisplay[i] = '_'; 
 }
 }
 
 // Method containing the game loop
 public void gameLoop() {
 Board board = new Board();
 UserInput userinput = new UserInput();
 
 // Game loop
 while(running) {
 board.printBoard(hangmanWordDisplay, usedCharacters, usedWords);
 String character = userinput.gameInput();
 inputChecking(character);
 
 }
 if(win){
 board.printBoard(hangmanWordDisplay, usedCharacters, usedWords);
 System.out.println("You have won");
 }else {
 System.out.println("You have lost, the word you were looking for is " + hangmanWord);
 }
 }
 
 // Checks whether the input is a single character or if it is a word
 public void inputChecking(String characterOrWord) {
 if(characterOrWord.length() == 1) {
 if(Character.isLetter(characterOrWord.charAt(0))) {
 inputCheckingCharacter(characterOrWord.charAt(0));
 }else {
 System.out.println("What you entered is not a character");
 return;
 }
 }else {
 inputCheckingWord(characterOrWord);
 }
 }
 
 //Checks if the word has been used before and checks if the word is the correct word
 public void inputCheckingWord(String wordInput) {
 if(word.hasUsedWord(usedWords, wordInput)){
 System.out.println("You have already used this tried this word");
 }else {
 addToUsedWords(wordInput);
 if(word.testWord(wordInput, hangmanWord)) {
 running = false;
 }else {
 misses++;
 Board board = new Board();
 board.writeToBoard(misses);
 running = wrongInputGameOver();
 return;
 }
 
 }
 }
 
 //Checks if the character has been used before and checks if the character is correct 
 public void inputCheckingCharacter(char inputChar) {
 boolean correct = false;
 if(word.hasUsedChar(usedCharacters, inputChar)){
 System.out.println("You have already used this character");
 }else {
 addToUsedCharacters(inputChar);
 for(int i = 0; i < hangmanWord.length(); i++) {
 if(word.testCharacter(inputChar, hangmanWord.charAt(i))) {
 hangmanWordDisplay[i] = inputChar;
 correct = true;
 if(checkCharacterInputWin()){
 running = false;
 win = true;
 }
 }else {
 if(!correct && i == hangmanWord.length() - 1) {
 misses++;
 Board board = new Board();
 board.writeToBoard(misses);
 running = wrongInputGameOver();
 return;
 }
 }
 }
 }
 }
 
 public boolean checkCharacterInputWin() {
 boolean test = false;
 for(int i = 0; i < hangmanWordDisplay.length; i++) {
 if(word.equalsIgnoreCase(hangmanWordDisplay[i], hangmanWord.charAt(i))) {
 test = true;
 }else {
 return false;
 }
 }
 return true;
 
 }
 
 // Checks if the player loses because he has made to many mistakes
 public boolean wrongInputGameOver() {
 if(misses == 8) {
 return false;
 }
 return true;
 }
 
 //Adds the inputed words to the usedWords array
 public void addToUsedWords(String word) {
 for(int i = 0; i < usedWords.length; i++) {
 if(usedWords[i] == null) {
 usedWords[i] = word;
 break;
 }
 }
 }
 
 //Adds the char to the usedCharacter array
 public void addToUsedCharacters(char inputChar) {
 for(int i = 0; i < usedCharacters.length; i++) {
 if(usedCharacters[i] == '\u0000') {
 usedCharacters[i] = inputChar;
 break;
 }
 }
 }
}
Piwoot
  • 303
  • 3
  • 7
lang-java

AltStyle によって変換されたページ (->オリジナル) /