Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Complete hangman game: Good example for seeing how everything goes together

  1. #1
    Junior Member ShadeDarkan's Avatar
    Join Date
    Jul 2012
    Location
    Houston, TX
    Posts
    13
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Complete hangman game: Good example for seeing how everything goes together

    I learned a lot of programming through courses and on my own, but it took me a long time to really figure out how to use all that functionality together. When and where to put functions, classes and just what worked with what. I created this hangman game for my Java I class, although, back then it was implemented a bit differently. Here's a more complex example of using different Java elements with each other for those of you who find most examples to be too simple for what they need.
    This is probably not the nicest code in the world, but hey, I'm still a beginner.

    There are two folders that I used to keep the words files and player statistics files in. These were Words and Save. Both file types are .txt for easy manipulation outside of the program.
    The Words folder contains three text files called Easy, Medium and Hard. For easy words I choose three to five letter words entered one per line, medium was six to eight letter words and hard was anything over eight. You can add and remove words at your convenience to these files. Note, these three files must be there when the program starts and populated with at least one word or it will return an error.
    The Save folder contains files generated by the program and updated by the program. Both folders were located in the program's top level directory structure since the program uses relative paths to find them. The folder structure looks like:

    Hangman
    |_Main.java
    |_GameLogic.java
    |_GUI
    | |_MainFrame.java
    |_IO
    | |_IO.java
    |_Words
    | |_Easy.txt
    | |_Medium.txt
    | |_Hard.txt
    |_Save

    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:
    /**
     * @author ShadeDarkan
     */
     
    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
        }
    }

    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:
    /**
     * @author ShadeDarkan
     */
     
    package Hangman.GUI;//The package this class belongs to
     
    import Hangman.GameLogic;//Needed so we can evaluate the game, get new words, set and get player stats, etc
    import java.awt.*;//Needed for many of the GUI elements we are using
    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((6 - 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("6 guesses left!");
                setIsEnabledTrue();
            }
            if(jrbmiMedium.isSelected())
            {
                gameLogic.getNewGameWord(jrbmiMedium.getActionCommand());
                jlDisplayWord.setText(gameLogic.getDisplayWord());
                setStatsText();
                jtaMessage.setText("6 guesses left!");
                setIsEnabledTrue();
            }
            if(jrbmiHard.isSelected())
            {
                gameLogic.getNewGameWord(jrbmiHard.getActionCommand());
                jlDisplayWord.setText(gameLogic.getDisplayWord());
                setStatsText();
                jtaMessage.setText("6 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("\nYOU WON!");
                    setStatsText();
                }
                if(sGameStatus.contentEquals("lose"))
                {
                    jtaMessage.append("\nYOU 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] + "\n");
            jtaStats.append("Games won: " + iaPStats[1] + "\n");
     
            if(iaPStats[0] == 0)
            {
                jtaStats.append("Win percentage: 0%" + "\n");
            }
            else
            {
                jtaStats.append("Win percentage: " + ((int)((double)iaPStats[1] / (double)iaPStats[0] * 100)) + "%" + "\n");
            }
            jtaStats.append("Games played on Easy: " + iaPStats[2] + "\n");
            jtaStats.append("Games played on Medium: " + iaPStats[3] + "\n");
            jtaStats.append("Games played on Hard: " + iaPStats[4]);
        }
    }

    The GameLogic class holds the functions needed to evaluate the game progress, get and set player statistics, retrieve new words to guess, etc. Some functions I would have liked to put here, but accessing GUI elements from other classes didn't work well for me, lol:
    /**
     * @ShadeDarkan
     */
     
    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);
               }
            }
        }
    }

    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:
    /**
     * @author ShadeDarkan
     */
     
    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.");
                }
            }
        }
    }

  2. The Following 2 Users Say Thank You to ShadeDarkan For This Useful Post:

    suiluj89 (July 7th, 2012), Zomby (October 11th, 2012)


  3. #2
    Junior Member
    Join Date
    Jul 2012
    Posts
    1
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Complete hangman game: Good example for seeing how everything goes together

    These is great! thanks

  4. #3
    Junior Member ShadeDarkan's Avatar
    Join Date
    Jul 2012
    Location
    Houston, TX
    Posts
    13
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: Complete hangman game: Good example for seeing how everything goes together

    Thanks. It only took four or five hours to code that. If anyone would like an example that uses some other Java functionality then just let me know.

Similar Threads

  1. Need a good rpg game idea..
    By Emperor_Xyn in forum Java Theory & Questions
    Replies: 5
    Last Post: January 3rd, 2012, 10:44 PM
  2. Hangman game for JAVA Beginning class
    By shahravi88 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 12th, 2011, 04:15 PM
  3. Hangman Game
    By Snow_Fox in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 29th, 2010, 04:07 PM
  4. Hangman game HELP!
    By KingFisher in forum What's Wrong With My Code?
    Replies: 11
    Last Post: September 9th, 2010, 05:23 AM
  5. Java hangman game help...
    By AnotherNoob in forum AWT / Java Swing
    Replies: 16
    Last Post: December 4th, 2009, 11:17 PM