Need help with java program assignment. I need help with these parts of the java
ID: 3692952 • Letter: N
Question
Need help with java program assignment. I need help with these parts of the java program assignment (the bold words):
-------------------------------------------------------------------------------------------------------------------
Hangman Game
Write a java program that is able to pick a random word from a list of words contained in a file and lets the user who is interacting with the game guess it one character at a time.
Upon startup, the player must be prompted for their name.
While playing, the player may guess at most 5 incorrect times. If the player guesses a character that has already been tried, he or she must NOT be penalized for doing so (i.e., it will not count as a turn).
The game ends when the full word has been guessed (player wins) or when five incorrect guesses have been made.
If the input file contains lines with numbers, a semicolon (;) or with a hashmark (#), those lines must be ignore.
Upon completion of the game, the player's name, the number of turns played, the word that should have been guessed, and an indicator for win/lose must be added to a file.
-----------------------------------------------------------------------------------------------------------
package hangman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Hangman {
public void playGame(String word) throws IOException {
Scanner sc = new Scanner(System.in);
FileWriter writer = new FileWriter("wordsnew.txt");
char[] guessArray = setDefaultCharArray(word.length());
char[] wordArray = word.toCharArray();
int numGuess = 0;
int numCorrect = 0;
while (!isWordComplete(guessArray) && numGuess < 5) {
System.out.print("Current word: ");
printCharArray(guessArray);
System.out.println();
System.out.print("Enter your guess: ");
char guess = sc.next().charAt(0);
boolean found = false;
for (int i = 0; i < guessArray.length; i++) {
if (guessArray[i] == '_' && wordArray[i] == guess) {
numCorrect++;
guessArray[i] = wordArray[i];
found = true;
}
}
if (!found) {
numGuess++;
}
System.out.println(numCorrect + " letters found");
System.out.println();
if (numGuess == 5) {
System.out.println();
System.out.println("Sorry, you lost.");
writer.write("Sorry, you lost.");
} else if (isWordComplete(guessArray))
System.out.println("You had won");
writer.write("You had won");
}
writer.close();
System.out.println("The word is " + word);
System.out.println("Total " + (numGuess) + " guesses");
System.out.println("Total " + (numGuess + numCorrect) + " attempts");
}
/**
* This method counts the number of words in a given file and returns that
* number.
*
* @methodName getNumberOfWordsInFile
* @param fileName
* @return wordCount
* @throws FileNotFoundException
*/
public int getNumberOfWordsInFile(String fileName) throws FileNotFoundException {
int wordCount = 0;
File file = new File("word.txt");
Scanner sc = new Scanner(new FileInputStream(file));
int count = 0;
while (sc.hasNext()) {
sc.next();
wordCount++;
}
return wordCount;
}
/**
* This method accepts a file name. First it gets the number of words in the
* file by calling the getNumberOfWordsInFile method. Then it creates a
* String array based on how many words are in the file. Next, it fills the
* array with all of the words from the file. Then it returns the array.
*
* @methodName getWordsFromFile
* @param fileName
* @return wordArray
* @throws FileNotFoundException
*/
public String[] getWordsFromFile(String fileName) throws FileNotFoundException {
int wordCount = getNumberOfWordsInFile("word.txt");
String[] wordArray = new String[wordCount];
File file = new File("word.txt");
Scanner sc = new Scanner(new FileInputStream(file));
int i = 0;
while (sc.hasNext()) {
wordArray[i] = sc.next();
i++;
}
sc.close();
return wordArray;
}
/**
* This method returns a random string from a given String array
*
* @methodName getRandomWord
* @param wordArray
* @return randomWord
*/
public String getRandomWord(String[] wordArray) {
String randomWord = null;
Random rd = new Random();
try {
int count = getNumberOfWordsInFile("word.txt");
int randNo = rd.nextInt(count - 1);
randomWord = wordArray[randNo];
while (count - 1 < randNo) {
if (count - 1 < randNo) {
randomWord = wordArray[randNo];
break;
} else
randNo = rd.nextInt(count - 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return randomWord;
}
/**
* This method accepts an int and creates a char array of that size Then it
* sets each element in the array to an underscore '_' Then it returns the
* char array.
*
* @methodName setDefaultCharArray
* @param size
* @return charArray
*/
public char[] setDefaultCharArray(int size) {
char[] charArray = new char[size];
for (int i = 0; i < charArray.length; i++)
charArray[i] = '_';
return charArray;
}
/**
* This method takes the given char array and uses a loop to print out each
* element all on the same line.
*
* @methodName printCharArray
* @param charArray
*/
public void printCharArray(char[] charArray) {
for (int i = 0; i < charArray.length; i++)
System.out.print(charArray[i]);
}
/**
* This method takes the given char array and checks if any of the elements
* are equal to an underscore '_' It returns true if the char array contains
* an underscore '_' and false if it does not.
*
* @methodName isWordComplete
* @param charArray
* @return isComplete
*/
public boolean isWordComplete(char[] charArray) {
boolean isComplete = true;
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == '_') {
isComplete = false;
break;
}
}
return isComplete;
}
}
package hangman;
import java.util.Scanner;
public class HangmanDriver {
public static void main(String[] args) throws Exception {
Hangman game = new Hangman();
System.out.print("Enter your name: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String[] wordArray = game.getWordsFromFile("word.txt");
String word = game.getRandomWord(wordArray);
game.playGame(word);
}
}
Explanation / Answer
Please follow the code and comments for description :
The folder structure looks like:
Hangman
|_Main.java
|_GameLogic.java
|_GUI
| |_MainFrame.java
|_IO
| |_IO.java
|_Words
| |_Easy.txt
| |_Medium.txt
| |_Hard.txt
|_Save
CODE :
1) This is the main.java file. The entire program starts here which creates a new instance of the GUI class MainFrame and sets its properties:
package Hangman;//The package this class belongs to
import Hangman.GUI.MainFrame;//Needed to create the GUI for the program
import javax.swing.JFrame;//Needed so we can set the properties of MainFrame as MainFrame uses JFrame
public class Main
{
public static void main(String[] args)
{
MainFrame mainFrame = new MainFrame();//Create a new instance of the GUI class
mainFrame.pack();//Size the JFrame to how big is needs to be to show all the elements inside it
mainFrame.setResizable(false);//Don't let the user resize the frame
mainFrame.setVisible(true);//Let the user see the JFrame
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//When the JFrame is closed, exit the program
mainFrame.setLocation(0, 0);//Set the default on-screen location of the JFrame
}
}
2) The MainFrame class controls the GUI elements and monitors when the user has interacted with the GUI by clicking a button or changing a menu setting. It's the biggest class, but 94% of it is simply creating the GUI elements and setting their properties:
package Hangman.GUI;
import Hangman.GameLogic;//Needed so we can evaluate the game, get new words, set and get player stats, etc
import java.awt.*;
import java.awt.event.ActionEvent;//Needed so we can make and use ActionEvent for our ActionListener
import java.awt.event.ActionListener;//Needed so we can tell when a button or menu item is clicked or changed
import javax.swing.*;//Needed for many of the GUI elements we are using
public class MainFrame extends JFrame
{
//Create global variables and objects
GameLogic gameLogic = new GameLogic();//Create a new GameLogic object so we can use its methods
private String sPlayerName = "";//We need this because the GUI is going to be getting the player's name and passing it to GameLogic
private String sGameStatus = "";//We need this to keep track of the game's win, lose or progressing status
//Create menu bars and items
private JMenuItem jmiNewGame = new JMenuItem("New Game");
private JMenuItem jmiChoosePlayer = new JMenuItem("Choose Player");
private JMenu jmDifficulty = new JMenu("Difficulty");
private JMenuItem jmiExit = new JMenuItem("Exit");
private JRadioButtonMenuItem jrbmiEasy = new JRadioButtonMenuItem("Easy", true);
private JRadioButtonMenuItem jrbmiMedium = new JRadioButtonMenuItem("Medium");
private JRadioButtonMenuItem jrbmiHard = new JRadioButtonMenuItem("Hard");
//Create stats and message text boxes
private JLabel jlDisplayWord = new JLabel();
private JTextArea jtaStats = new JTextArea();
private JTextArea jtaMessage = new JTextArea();
//Create the alphabet buttons
private JButton jbtA = new JButton("A");
private JButton jbtB = new JButton("B");
private JButton jbtC = new JButton("C");
private JButton jbtD = new JButton("D");
private JButton jbtE = new JButton("E");
private JButton jbtF = new JButton("F");
private JButton jbtG = new JButton("G");
private JButton jbtH = new JButton("H");
private JButton jbtI = new JButton("I");
private JButton jbtJ = new JButton("J");
private JButton jbtK = new JButton("K");
private JButton jbtL = new JButton("L");
private JButton jbtM = new JButton("M");
private JButton jbtN = new JButton("N");
private JButton jbtO = new JButton("O");
private JButton jbtP = new JButton("P");
private JButton jbtQ = new JButton("Q");
private JButton jbtR = new JButton("R");
private JButton jbtS = new JButton("S");
private JButton jbtT = new JButton("T");
private JButton jbtU = new JButton("U");
private JButton jbtV = new JButton("V");
private JButton jbtW = new JButton("W");
private JButton jbtX = new JButton("X");
private JButton jbtY = new JButton("Y");
private JButton jbtZ = new JButton("Z");
//Class constructor
public MainFrame()
{
//Create menu bar and items
JMenuBar jmbMenu = new JMenuBar();
JMenu jmGameOptions = new JMenu("Game Options");
//Create panel for GUI elements
JPanel jpMenu = new JPanel();
JPanel jpLabel = new JPanel();
JPanel jpImagesText = new JPanel();
JPanel jpImages = new JPanel();
JPanel jpText = new JPanel();
JPanel jpButtons = new JPanel();
//Create the button group for difficulties
ButtonGroup bgDifficulty = new ButtonGroup();
//Create dimension objects for use with JLabel to set a preferred size for the GUI element
Dimension dLabel = new Dimension();
Dimension dImagesText = new Dimension();
//Set the layout for panels
setLayout(new GridBagLayout());
jpMenu.setLayout(new FlowLayout(FlowLayout.LEFT));
jpLabel.setLayout(new FlowLayout(FlowLayout.CENTER));
jpImagesText.setLayout(new GridLayout(1,2,5,0));
jpText.setLayout(new GridLayout(2, 1, 0, 5));
jpButtons.setLayout(new GridLayout(2, 13, 0, 0));
//Set component properties
jtaStats.setEditable(false);
jtaStats.setLineWrap(true);
jtaMessage.setEditable(false);
jtaMessage.setLineWrap(true);
jlDisplayWord.setFont(jlDisplayWord.getFont().deriveFont(46.0f));
dLabel.height = 80;
dImagesText.height = 300;
jpLabel.setPreferredSize(dLabel);
jpImagesText.setPreferredSize(dImagesText);
//Add menu items to the menu
jmbMenu.add(jmGameOptions);
jmGameOptions.add(jmiNewGame);
jmGameOptions.add(jmiChoosePlayer);
jmGameOptions.add(jmDifficulty);
jmGameOptions.add(jmiExit);
jmDifficulty.add(jrbmiEasy);
jmDifficulty.add(jrbmiMedium);
jmDifficulty.add(jrbmiHard);
bgDifficulty.add(jrbmiEasy);
bgDifficulty.add(jrbmiMedium);
bgDifficulty.add(jrbmiHard);
//Create GUI constraints
GridBagConstraints cMenu = new GridBagConstraints();
cMenu.anchor = GridBagConstraints.LINE_START;
cMenu.gridwidth = GridBagConstraints.REMAINDER;
cMenu.gridx = 0;
cMenu.gridy = 0;
GridBagConstraints cLabel = new GridBagConstraints();
cLabel.fill = GridBagConstraints.BOTH;
cLabel.gridwidth = GridBagConstraints.REMAINDER;
cLabel.gridy = GridBagConstraints.RELATIVE;
GridBagConstraints cImagesText = new GridBagConstraints();
cImagesText.fill = GridBagConstraints.BOTH;
cImagesText.gridwidth = GridBagConstraints.REMAINDER;
cImagesText.gridy = GridBagConstraints.RELATIVE;
GridBagConstraints cButtons = new GridBagConstraints();
cButtons.fill = GridBagConstraints.BOTH;
cButtons.gridwidth = GridBagConstraints.REMAINDER;
cButtons.gridy = GridBagConstraints.RELATIVE;
//Add the panels to the MainFrame
this.add(jpMenu, cMenu);
jpMenu.add(jmbMenu);
this.add(jpLabel, cLabel);
jpLabel.add(jlDisplayWord);
this.add(jpImagesText, cImagesText);
jpImagesText.add(jpImages);
jpImagesText.add(jpText);
this.add(jpButtons, cButtons);
//Add the text areas to the panels
jpText.add(jtaStats);
jpText.add(jtaMessage);
//Add buttons to jpButtons panel
jpButtons.add(jbtA);
jpButtons.add(jbtB);
jpButtons.add(jbtC);
jpButtons.add(jbtD);
jpButtons.add(jbtE);
jpButtons.add(jbtF);
jpButtons.add(jbtG);
jpButtons.add(jbtH);
jpButtons.add(jbtI);
jpButtons.add(jbtJ);
jpButtons.add(jbtK);
jpButtons.add(jbtL);
jpButtons.add(jbtM);
jpButtons.add(jbtN);
jpButtons.add(jbtO);
jpButtons.add(jbtP);
jpButtons.add(jbtQ);
jpButtons.add(jbtR);
jpButtons.add(jbtS);
jpButtons.add(jbtT);
jpButtons.add(jbtU);
jpButtons.add(jbtV);
jpButtons.add(jbtW);
jpButtons.add(jbtX);
jpButtons.add(jbtY);
jpButtons.add(jbtZ);
//Create button action listeners
MenuListener menuListener = new MenuListener();
ButtonListener buttonListener = new ButtonListener();
//Register the action listener with the buttons
jmiNewGame.addActionListener(menuListener);
jmiChoosePlayer.addActionListener(menuListener);
jmDifficulty.addActionListener(menuListener);
jmiExit.addActionListener(menuListener);
jrbmiEasy.addActionListener(menuListener);
jrbmiMedium.addActionListener(menuListener);
jrbmiHard.addActionListener(menuListener);
jbtA.addActionListener(buttonListener);
jbtB.addActionListener(buttonListener);
jbtC.addActionListener(buttonListener);
jbtD.addActionListener(buttonListener);
jbtE.addActionListener(buttonListener);
jbtF.addActionListener(buttonListener);
jbtG.addActionListener(buttonListener);
jbtH.addActionListener(buttonListener);
jbtI.addActionListener(buttonListener);
jbtJ.addActionListener(buttonListener);
jbtK.addActionListener(buttonListener);
jbtL.addActionListener(buttonListener);
jbtM.addActionListener(buttonListener);
jbtN.addActionListener(buttonListener);
jbtO.addActionListener(buttonListener);
jbtP.addActionListener(buttonListener);
jbtQ.addActionListener(buttonListener);
jbtR.addActionListener(buttonListener);
jbtS.addActionListener(buttonListener);
jbtT.addActionListener(buttonListener);
jbtU.addActionListener(buttonListener);
jbtV.addActionListener(buttonListener);
jbtW.addActionListener(buttonListener);
jbtX.addActionListener(buttonListener);
jbtY.addActionListener(buttonListener);
jbtZ.addActionListener(buttonListener);
}
//Action listener for menu items
private class MenuListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sMenuPressed = e.getActionCommand();//Get the item that was pressed or selected
//Evaluate the menu selection and take action if needed
if(sMenuPressed.contentEquals("New Game"))
{
if(sPlayerName.contentEquals(""))
{
setPlayerName();
}
startNewGame();
}
if(sMenuPressed.contentEquals("Choose Player"))
{
setPlayerName();
startNewGame();
}
if(sMenuPressed.contentEquals("Easy"))
{
if(sPlayerName.contentEquals(""))
{
setPlayerName();
}
startNewGame();
}
if(sMenuPressed.contentEquals("Medium"))
{
if(sPlayerName.contentEquals(""))
{
setPlayerName();
}
startNewGame();
}
if(sMenuPressed.contentEquals("Hard"))
{
if(sPlayerName.contentEquals(""))
{
setPlayerName();
}
startNewGame();
}
if(sMenuPressed.contentEquals("Exit"))
{
System.exit(0);
}
}
}
//Action listener for button items
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(sGameStatus.contentEquals("progressing"))
{
//Change action into a character
String sBtnPressed = e.getActionCommand();
char[] chaBtn = sBtnPressed.toCharArray();
char chBtn = chaBtn[0];
//Send action for button greyout
setIsEnabledFalse(chBtn);
//Send action to game logic for evaluation
gameLogic.EvaluateGuess(chBtn, e.getActionCommand());
jlDisplayWord.setText(gameLogic.getDisplayWord());
sGameStatus = gameLogic.EvaluateGame();
jtaMessage.setText((5 - gameLogic.getGuessesMade()) + " guesses left!");
evalGameStatus();
}
}
}
//Starts a new game
private void startNewGame()
{
if(jrbmiEasy.isSelected())
{
gameLogic.getNewGameWord(jrbmiEasy.getActionCommand());
jlDisplayWord.setText(gameLogic.getDisplayWord());
setStatsText();
jtaMessage.setText("5 guesses left!");
setIsEnabledTrue();
}
if(jrbmiMedium.isSelected())
{
gameLogic.getNewGameWord(jrbmiMedium.getActionCommand());
jlDisplayWord.setText(gameLogic.getDisplayWord());
setStatsText();
jtaMessage.setText("5 guesses left!");
setIsEnabledTrue();
}
if(jrbmiHard.isSelected())
{
gameLogic.getNewGameWord(jrbmiHard.getActionCommand());
jlDisplayWord.setText(gameLogic.getDisplayWord());
setStatsText();
jtaMessage.setText("5 guesses left!");
setIsEnabledTrue();
}
sGameStatus = "progressing";
}
//Evaluate game status
private void evalGameStatus()
{
if(sGameStatus.contentEquals("win") || sGameStatus.contentEquals("lose"))
{
if(jrbmiEasy.isSelected())
{
gameLogic.setPlayerStats(sPlayerName, sGameStatus,
jrbmiEasy.getActionCommand());
}
if(jrbmiMedium.isSelected())
{
gameLogic.setPlayerStats(sPlayerName, sGameStatus,
jrbmiMedium.getActionCommand());
}
if(jrbmiHard.isSelected())
{
gameLogic.setPlayerStats(sPlayerName, sGameStatus,
jrbmiHard.getActionCommand());
}
if(sGameStatus.contentEquals("win"))
{
jtaMessage.append(" YOU WON!");
setStatsText();
}
if(sGameStatus.contentEquals("lose"))
{
jtaMessage.append(" YOU LOST!");
setStatsText();
jlDisplayWord.setText(gameLogic.getRealWord());
}
}
}
//Sets the alphabet button pressed to not enabled
private void setIsEnabledFalse(char chBtn)
{
switch (chBtn)
{
case 'A': jbtA.setEnabled(false); break;
case 'B': jbtB.setEnabled(false); break;
case 'C': jbtC.setEnabled(false); break;
case 'D': jbtD.setEnabled(false); break;
case 'E': jbtE.setEnabled(false); break;
case 'F': jbtF.setEnabled(false); break;
case 'G': jbtG.setEnabled(false); break;
case 'H': jbtH.setEnabled(false); break;
case 'I': jbtI.setEnabled(false); break;
case 'J': jbtJ.setEnabled(false); break;
case 'K': jbtK.setEnabled(false); break;
case 'L': jbtL.setEnabled(false); break;
case 'M': jbtM.setEnabled(false); break;
case 'N': jbtN.setEnabled(false); break;
case 'O': jbtO.setEnabled(false); break;
case 'P': jbtP.setEnabled(false); break;
case 'Q': jbtQ.setEnabled(false); break;
case 'R': jbtR.setEnabled(false); break;
case 'S': jbtS.setEnabled(false); break;
case 'T': jbtT.setEnabled(false); break;
case 'U': jbtU.setEnabled(false); break;
case 'V': jbtV.setEnabled(false); break;
case 'W': jbtW.setEnabled(false); break;
case 'X': jbtX.setEnabled(false); break;
case 'Y': jbtY.setEnabled(false); break;
case 'Z': jbtZ.setEnabled(false); break;
}
}
//Sets the alphabet buttons back to enabled
private void setIsEnabledTrue()
{
jbtA.setEnabled(true); jbtN.setEnabled(true);
jbtB.setEnabled(true); jbtO.setEnabled(true);
jbtC.setEnabled(true); jbtP.setEnabled(true);
jbtD.setEnabled(true); jbtQ.setEnabled(true);
jbtE.setEnabled(true); jbtR.setEnabled(true);
jbtF.setEnabled(true); jbtS.setEnabled(true);
jbtG.setEnabled(true); jbtT.setEnabled(true);
jbtH.setEnabled(true); jbtU.setEnabled(true);
jbtI.setEnabled(true); jbtV.setEnabled(true);
jbtJ.setEnabled(true); jbtW.setEnabled(true);
jbtK.setEnabled(true); jbtX.setEnabled(true);
jbtL.setEnabled(true); jbtY.setEnabled(true);
jbtM.setEnabled(true); jbtZ.setEnabled(true);
}
//Set the player's name
private void setPlayerName()
{
sPlayerName = JOptionPane.showInputDialog(null, "Enter your name:",
"Player Name", JOptionPane.QUESTION_MESSAGE);
}
//Update stats text area
private void setStatsText()
{
int[] iaPStats = gameLogic.getPlayerStats(sPlayerName);
jtaStats.setText("");
jtaStats.append("Games played: " + iaPStats[0] + " ");
jtaStats.append("Games won: " + iaPStats[1] + " ");
if(iaPStats[0] == 0)
{
jtaStats.append("Win percentage: 0%" + " ");
}
else
{
jtaStats.append("Win percentage: " + ((int)((double)iaPStats[1] / (double)iaPStats[0] * 100)) + "%" + " ");
}
jtaStats.append("Games played on Easy: " + iaPStats[2] + " ");
jtaStats.append("Games played on Medium: " + iaPStats[3] + " ");
jtaStats.append("Games played on Hard: " + iaPStats[4]);
}
}
3) The GameLogic class holds the functions needed to evaluate the game progress, get and set player statistics, retrieve new words to guess, etc.
package Hangman;
import Hangman.IO.IO;
import javax.swing.JOptionPane;
public class GameLogic
{
//Create member variables
private final String sWordFolder = "Words";
private final String sSaveFolder = "Save";
private IO ioGame = new IO();
private String sRealWord = "";
private String sDisplayWord = "";
private int[] iaPStats = new int[5];
private int iGuessesMade;
//Class consructor
public GameLogic()
{
iGuessesMade = 0;//Set the guesses made to zero
}
//Get the player's saved stats, if available
public int[] getPlayerStats(String sPlayerName)
{
try//Send the player's name to IO so IO can check for a player save file to pull stats from
{
iaPStats = ioGame.getPlayerStats((sPlayerName + ".txt"), sSaveFolder, iaPStats);
}
catch(Exception e)//Display any error messages if IO can't get player stats
{
JOptionPane.showMessageDialog(null,e.toString(),"IO Error", JOptionPane.ERROR_MESSAGE);
}
return iaPStats;
}
//Return the string to be displayed to the player
public String getDisplayWord()
{
return sDisplayWord;
}
//Return the real word
public String getRealWord()
{
return sRealWord;
}
//Return the number of guesses made
public int getGuessesMade()
{
return iGuessesMade;
}
//Retrieve a new word
public void getNewGameWord(String difficulty)
{
try
{
//Get a new word and update real word string
sRealWord = ioGame.getRandomWord((difficulty + ".txt"), sWordFolder);
//Set the display word string to all '+'
char[] chaDisplayWord = new char[sRealWord.length()];
for(int i = 0; i < sRealWord.length(); i++)
{
chaDisplayWord[i] = '+';
}
String sTempWord = new String(chaDisplayWord);
sDisplayWord = sTempWord;
//Reset guesses made to 0
iGuessesMade = 0;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString(),"IO Error", JOptionPane.ERROR_MESSAGE);
}
}
//Evaluate a character guess and update the display word if needed
public void EvaluateGuess(char chGuess, String sGuess)
{
boolean bGuessMatch = false;
//Convert display and real word strings to char arrays
char[] chaRealWord = sRealWord.toCharArray();
char[] chaDisplayWord = sDisplayWord.toCharArray();
//Compare each character for matches and update display word
for(int i = 0; i < chaRealWord.length; i++)
{
if(chGuess == chaRealWord[i])
{
chaDisplayWord[i] = chaRealWord[i];
bGuessMatch = true;
}
}
//Penalize for wrong guesses
if(bGuessMatch == false)
{
iGuessesMade = (iGuessesMade + 1);
}
//Change display word char array to a string
String sTempWord = new String(chaDisplayWord);
sDisplayWord = sTempWord;
}
//Evaluate a game for win, loss, progressing condition
public String EvaluateGame()
{
if(sDisplayWord.equals(sRealWord))
{
return "win";
}
else if((iGuessesMade != 6) && (!sDisplayWord.contentEquals(sRealWord)))
{
return "progressing";
}
else if((iGuessesMade == 6) && (!sDisplayWord.contentEquals(sRealWord)))
{
return "lose";
}
return "error";
}
//Sets the player stats after a game
public void setPlayerStats(String sPlayerName, String sGameStatus, String sDifficulty)
{
if(sGameStatus.contentEquals("win"))
{
++iaPStats[0];
++iaPStats[1];
if(sDifficulty.contentEquals("Easy"))
{
++iaPStats[2];
}
else if(sDifficulty.contentEquals("Medium"))
{
++iaPStats[3];
}
else
{
++iaPStats[4];
}
try
{
ioGame.setPlayerStats((sPlayerName + ".txt"), iaPStats, sSaveFolder);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e.toString(),"IO Error", JOptionPane.ERROR_MESSAGE);
}
}
else
{
++iaPStats[0];
if(sDifficulty.contentEquals("Easy"))
{
++iaPStats[2];
}
else if(sDifficulty.contentEquals("Medium"))
{
++iaPStats[3];
}
else
{
++iaPStats[4];
}
try
{
ioGame.setPlayerStats((sPlayerName + ".txt"), iaPStats, sSaveFolder);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e.toString(),"IO Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
4) Then, for single responsibility sake I put all the input/output into its own class called IO. IO really just takes the information provided from GameLogic and either writes it to a file or reads it from a file:
package Hangman.IO;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class IO
{
public IO ()
{
}
//Look for a file <difficulty> in the directory <folder> to get a word from
public String getRandomWord(String difficulty, String folder) throws IOException
{
ArrayList alRandomWord = new ArrayList();//We are going to read the words from the file into the ArrayList
File fDirWords = new File(folder);//Create file object from the directory argument <folder>
//Check that the directory containing the files for the random words exists.
if(!fDirWords.exists() && !fDirWords.canRead())
{
throw new IOException("The " + folder + " folder is missing or corrupt. "
+ "Please repair the program");
}
else
{
//Create a file object from the directory <folder> and file <difficulty> arguments
File fRandomWord = new File(folder + "/" + difficulty);
if(fRandomWord.exists() && fRandomWord.canRead())
{
Scanner input = new Scanner(fRandomWord);//Create a scanner object from our directory/file file object so we can read the file
while(input.hasNext())//While the scanner has another word enter the loop
{
alRandomWord.add(input.next().toString());//Add each word read by the scanner object into the arraylist
}
input.close();//Make sure to close your scanner object when you don't need it
}
else
{
throw new IOException ("The " + difficulty + " file is corrupt or missing. "
+ "Please repair the program.");
}
}
Random rNumber = new Random();//Create a random object for generating random numbers
//Generate a random number in the range our arraylist length, access the word at that index, turn it into a string and put it in rWord
String rWord = alRandomWord.get(rNumber.nextInt(alRandomWord.size())).toString();
return rWord;
}
//Use the player name <sName>, directory <folder> and array to get the player's stats from a file
public int[] getPlayerStats(String sName, String folder, int[] iaPStats) throws IOException
{
File fDirSave = new File(folder);
if(!fDirSave.exists())
{
throw new IOException("The " + folder + " folder is missing or corrupt. "
+ "Please repair the program.");
}
else
{
File fPStats = new File(folder + "/" + sName);
if(fPStats.exists() && fPStats.canRead())
{
Scanner sPStats = new Scanner(fPStats);
for(int i = 0; i < (iaPStats.length - 1); i++)
{
if(sPStats.hasNextInt())
{
iaPStats[i] = sPStats.nextInt();
}
else
{
iaPStats[i] = 0;
}
}
}
else if(!fPStats.exists())
{
fPStats.createNewFile();
for(int i = 0; i < (iaPStats.length - 1); i++)
{
iaPStats[i] = 0;
}
throw new IOException("The " + sName + " file could not be found. "
+ "A new file has been created.");
}
}
return iaPStats;
}
//Use the player's name <sName>, directory <sFolder> and stats array <iaStats> to write the player's stats to their save file
public void setPlayerStats(String sName, int[] iaStats, String sfolder) throws IOException
{
File fDirSave = new File(sfolder);
if(!fDirSave.exists())
{
throw new IOException("The " + sfolder + " folder is missing or corrupt. "
+ "Please repair the program.");
}
else
{
File fPStats = new File(sfolder + "/" + sName);
if(fPStats.exists() && fPStats.canRead())
{
PrintWriter pwPStats = new PrintWriter(fPStats);//Create a printwriter object (streamout) to write the stats to file
for(int i = 0; i < iaStats.length; i++)
{
pwPStats.println(iaStats[i]);
}
pwPStats.close();//Make sure to close the printwriter object when you are done with it
}
else
{
throw new IOException("The " + sName + " file is missing or corrupt. "
+ "No data was saved.");
}
}
}
}
There have been some changes done to the code. But hope this is helpful.