Results 1 to 7 of 7

Thread: Need some serious Hangman Help [JAVA]

  1. #1
    Join Date
    Dec 2011
    Posts
    45
    Mentioned
    0 Post(s)
    Quoted
    11 Post(s)

    Question Need some serious Hangman Help [JAVA]

    I restarted my code and managed to figure everything out. I'll post it on here if anyone is interested about how I got it to work. Thanks though

  2. #2
    Join Date
    Sep 2012
    Location
    Here.
    Posts
    2,007
    Mentioned
    88 Post(s)
    Quoted
    1014 Post(s)

    Default

    I'm not a GUI person at all. I've always been a back-end guy. With that in mind, @NKN should come in here and help you

  3. #3
    Join Date
    Feb 2007
    Location
    PA, USA
    Posts
    5,240
    Mentioned
    36 Post(s)
    Quoted
    496 Post(s)

    Default

    Can i suggest you get the logic working without a gui first? you can easily test stuff with sys.out.println or with jpanes of you want a window. Also, use stringbuilder instead of your ugly way of formatting that text... :P

  4. #4
    Join Date
    Mar 2012
    Location
    127.0.0.1
    Posts
    3,383
    Mentioned
    95 Post(s)
    Quoted
    717 Post(s)

    Default

    Quote Originally Posted by Kevin View Post
    I'm not a GUI person at all. I've always been a back-end guy. With that in mind, @NKN should come in here and help you
    I suck really bad at GUIs

    @Brandon We'll pass this along until someone helps. :3

  5. #5
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Quote Originally Posted by footballjds View Post
    Can i suggest you get the logic working without a gui first? you can easily test stuff with sys.out.println or with jpanes of you want a window. Also, use stringbuilder instead of your ugly way of formatting that text... :P
    Why does everyone suggest stringbuilder :S
    Stringbuilder is far uglier than using the + operator. Secondly, the + operator implicitly uses the StringBuilder for appending under the hood so there is no optimization gains.

    In fact, there's a performance loss. The compiler already uses a stringbuilder for concatenation. Using a second one or more will just have it create another and continue in that cycle. You'd end up having one from the compiler and one from you.

    Only time you gain anything from using string builder is in loops. Only old JVM's require the use of it all the time because the + operator doesn't use it.


    When I run, the frame will not show up until you have lost
    @Op.. The reason your frame doesn't show is because you have all your processing in the PanelHangTeacher constructor. Thus the object never actually finishes constructing at all. It's like having an infinite loop in the constructor of any class. To fix it, simply allow your class to construct and put all the logic in separate functions. Call those functions after your frame and panel is visible and finished constructing.

    The way you structured your program right now is pretty bad. The way you have it right now, it goes like this:

    Java Code:
    Constructor() {
        //Initialize variables and read files..
        Start(); //call start function.
    }

    Start() {
       //Loop and do other stuff.
       //call choose random.. etc..
       ChoosePerson();  //call choose person..
       Guess(); //call guess..
    }

    ChoosePerson() {
        //Do processing..
    }

    Guess() {
       //Loop and do other stuff..
       GuessLetter(); //call guess letter.
    }

    GuessLetter() {
       //Loop and do other stuff..
     
    }
    .
    .
    .
    .

    Oh and please use syntax highlighting other than plain-text formatting.
    Last edited by Brandon; 08-06-2013 at 10:27 PM.
    I am Ggzz..
    Hackintosher

  6. #6
    Join Date
    Dec 2011
    Location
    Toronto, Ontario
    Posts
    6,424
    Mentioned
    84 Post(s)
    Quoted
    863 Post(s)

    Default

    Didn't see this thread, and @Kevin y u no mention me D:

    Here's my Hangman which I got 100% on:

    java Code:
    //Title: Hangman
    //Author: Shay H, last updated 16/06/2013
    //Purpose: Bonus Assignment

    /*Extra Features:
                - File Reading
                - Guess box, allows you to enter your guess
                - Detailed help document
                - Adds letters used to list
                - Only allows one letter to be inputted at a time  
    */


    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Random;

    public class Hangman extends Applet implements ActionListener
    {
        String lettersUsedString = "Letters used: ";    //creates a string to be used in lettersUsed textfield

        //JPanels   - creates panels used for various components
        JPanel titlePanel;  //stores the title
        JPanel imagePanel;  //stores the image
        JPanel buttonPanel; //stores the buttons
        JPanel guessPanel;  //stores the textfields
        JPanel lPanel;      //stores the lettersUsed field
        JPanel hintPanel;   //stores the hint field

        //Labels
        JLabel titleLabel;          //title label
        JLabel image;               //image label
        JLabel incorrectGuesses;    //incorrect guess label
        JLabel hint;                //hint label

        //Image Array - an array of image aths
        String hangManStatus[] = {"hangmanEmpty.png", "hangmanHead.png", "hangmanBody.png", "hangman1Arm.png", "hangman2Arm.png", "hangman1Leg.png", "hangmanDead.png"};

        //JTextFields
        JTextField characterEntry;  //character entry field
        JTextField guessEntry;      //guess entry field
        JTextField lettersUsed;     //letters used field
        JTextField hintField;       //hint used field

        //JButton
        JButton charEntry;          //char entry button
        JButton guEntry;            //guess entry button

        //Movie Array
        String movies[] = new String [214];

        //Strings   - strings used
        String movie;
        char[] sMovie;

        //Integers
        int status = 0;

        public void init ()
            //Pre: No conditions must be met.
            //Post: Creates an applet with components.
        {
            int reply = JOptionPane.showConfirmDialog (null, "Would you like to view the help document?", "Help", JOptionPane.YES_NO_OPTION);
            if (reply == JOptionPane.YES_OPTION)
            {
                JOptionPane.showMessageDialog(null, "Welcome to Hangman. The player has to guess a letter and if it's correct, you put it in the blank.\n" +
                                                   "If it's incorrect you put a head on the upside down L. Draw another body part for each subsequent wrong guess.\n" +
                                                   "The object is to guess the word before the body is completed. If you think you know the word, you can\n" +
                                                   "enter it in the bigger text field and press guess. Be warned, if you miss the answer, you lose the game!", "Help", JOptionPane.INFORMATION_MESSAGE);
            }
            if (reply == JOptionPane.CANCEL_OPTION)
            {
                System.exit (0);
            }


            setSize (450, 600); //sets the size
            setBackground (Color.lightGray);    //sets the background

            //Title Label definition
            titleLabel = new JLabel ("Hangman");    //creates the title
            titleLabel.setForeground (Color.blue);  //sets the color of the title
            titleLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 24)); //creates the font

            //Title Panel definition
            titlePanel = new JPanel ();
            titlePanel.add (titleLabel);    //adds the panel into title
            titlePanel.setBackground (Color.lightGray); //sets the panel color to gray

            //Image definition
            image = new JLabel (createImageIcon (hangManStatus [0]));   //sets the label image to the base hangman image

            //Image Panel definition
            imagePanel = new JPanel (); //creates the image
            imagePanel.setBackground (Color.lightGray); //sets the image to gray
            imagePanel.add (image); //adds the image to the panel

            //JTextField definitions
            buttonPanel = new JPanel ();
            characterEntry = new JTextField (5);
            guessEntry = new JTextField (15);
            lettersUsed = new JTextField (25);
            lettersUsed.setEnabled (false); //disables the field

            lettersUsed.setText (lettersUsedString);    //sets the text to lettersUsedString
            lPanel = new JPanel ();     //new panel
            lPanel.setBackground (Color.lightGray); //sets the background to light gray
            lPanel.add (lettersUsed);   //adds the field

            hintPanel = new JPanel ();
            hintField = new JTextField (25);
            hintField.setEnabled (false);
            hintPanel.add (hintField);
            hintPanel.setBackground (Color.lightGray);

            //JButton definitions
            //sets listeners
            charEntry = new JButton ("Check!");
            charEntry.setActionCommand ("check");
            charEntry.addActionListener (this);

            //sets listeners
            guEntry = new JButton ("Guess!");
            guEntry.setActionCommand ("guess");
            guEntry.addActionListener (this);

            //adds everything to the panel
            buttonPanel.add (characterEntry);
            buttonPanel.add (charEntry);
            buttonPanel.add (guessEntry);
            buttonPanel.add (guEntry);

            //JLabel definition
            incorrectGuesses = new JLabel ("Letters used: ");
            guessPanel = new JPanel ();
            hint = new JLabel ();
            guessPanel.add (hint);

            //reads the movie file
            readMovieFile ("movies.txt");

            /* Setting the seed */
            Random randomGenerator = new Random (); //creates a new random
            int randomInt = randomGenerator.nextInt (movies.length);    //new random int
            movie = movies [randomInt].toLowerCase ();  //creates a random movie and sets it to lowercase
            System.out.println (movie);
            sMovie = new char [movie.length ()];    //creates a new char array
            sMovie = stripString (movie);   //strips the string
            //System.out.println (sMovie);
            hintField.setText (new String (sMovie));    //sets the text to sMovie

            //Additions to GUI
            add (titlePanel);
            add (imagePanel);
            add (buttonPanel);
            buttonPanel.setBackground (Color.lightGray);
            add (guessPanel);
            guessPanel.setBackground (Color.lightGray);
            add (lPanel);
            add (hintPanel);
        }


        public char[] stripString (String m)
            //Pre: m must be a movie of length >0
            //Post: returns a string with * times the length of the string
        {
            char s[] = new char [m.length ()];  //creates a new char array with the length of m
            for (int i = 0 ; i < m.length () ; i++)
            {
                if (m.charAt (i) != ' ') //if the char at i is not a space,
                {
                    s [i] = '*';    //set the char at i to a *
                }
                else
                {
                    s [i] = ' ';    //keeps the char at i at a space
                }
            }
            return s;   //returns s
        }


        public void readMovieFile (String path)
            //Pre: Path must be valid
            //Post: Stores the lines in the path file to movies (an array)
        {
            File f = new File (path);   //creates a new instance of file
            BufferedReader br = null;   //creates a new instance of BufferedReader
            FileReader fr = null;       //creates a new instance of FileReader
            if (f.exists ())            //if file exists
            {
                try
                {
                    fr = new FileReader (f);
                    br = new BufferedReader (fr);

                    String line = null;     //sets the line to null
                    for (int i = 0 ; i < movies.length ; i++)
                    {
                        if ((line = br.readLine ()) != null)    //if the line isnt null
                            movies [i] = line;  //assign movies[i] to the movie at line line.
                    }
                }
                //catch various exceptions
                catch (FileNotFoundException e)
                {
                    e.printStackTrace ();
                }
                catch (IOException e)
                {
                    e.printStackTrace ();
                }
                finally
                {
                    try
                    {
                        if (br != null)
                        {
                            br.close ();
                        }
                        if (fr != null)
                        {
                            fr.close ();
                        }
                    }
                    catch (IOException e)
                    {
                    }
                }
            }

        }


        public void actionPerformed (ActionEvent e)
            //Pre: e must be an event
            //Post: returns various items. sets components, winning messages, etc.
        {
            if (e.getActionCommand ().equals ("check"))         //if the check button is pressed
            {
                String userGuess = (characterEntry.getText ());     //get the text out of the textfield
                System.out.println (userGuess);                     //print the userguess (debug)
                if (userGuess.length () > 1 && userGuess.length () > 0)     //if the length is bigger than 1, and bigger than 0
                {
                    JOptionPane.showMessageDialog (null, "Only one letter is permitted!", "Error!", JOptionPane.INFORMATION_MESSAGE);   //show this
                }
                else        //else
                {
                    int counter = 0;        //start a counter
                    for (int i = 0 ; i < movie.length () ; i++)
                    {
                        if (movie.charAt (i) == userGuess.charAt (0))       //if the charAt is equal to the guess
                        {
                            sMovie [i] = userGuess.charAt (0);              //set the guess correct
                            hintField.setText (new String (sMovie));
                        }
                        if (movie.charAt (i) != userGuess.charAt (0))
                        {
                            counter++;              //else counter++
                        }
                    }
                    System.out.println ("Counter: " + counter + ", Movie: " + movie.length ());
                    if (counter == movie.length ())
                    {
                        lettersUsedString += userGuess.charAt (0) + ", ";       //set lettersUsed to the guess
                        lettersUsed.setText (lettersUsedString);                //set the text
                        lettersUsed.repaint ();                                 //repaint
                        status++;
                        image.setIcon (createImageIcon (hangManStatus [status]));   //set the image
                    }
                }
                if (status == hangManStatus.length - 1)
                {
                    JOptionPane.showMessageDialog (null, "Aw man! You lost the game!\nRun the program again and try again!", "Game Over!", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);        //say lost game and exit
                }
                if (new String (sMovie).equalsIgnoreCase (movie)) //if the char array is equal to the movie
                {
                    JOptionPane.showMessageDialog (null, "Wow! You won the game! Run the program again to play again!", "Game Over!", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);        //say won game and exit
                }
            }
            if (e.getActionCommand ().equals ("guess"))     //if the action command is guess
            {
                String myguess = guessEntry.getText ();     //get the text from guessentry
                System.out.println (myguess);
                if (!myguess.equals (movie))           //if the guess doesnt equal
                {
                    JOptionPane.showMessageDialog (null, "Aw man! You lost the game!\nRun the program again and try again!", "Game Over!", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);    //say lost game and exit
                }
                if (myguess.equals (movie))
                {
                    JOptionPane.showMessageDialog (null, "Wow! You won the game! Run the program again to play again!", "Game Over!", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);    //say won game and exit
                }
            }
        }


        protected ImageIcon createImageIcon (String path)
            //Pre: path must be valid
            //Post: returns an icon
        {
            java.net.URL imgURL = getClass ().getResource (path);
            if (imgURL != null)
            {
                return new ImageIcon (imgURL);
            }
            else
            {
                return null;
            }
        }
    }

    Wont run because it's missing the movies file and images.

  7. #7
    Join Date
    Feb 2006
    Location
    Tracy/Davis, California
    Posts
    12,631
    Mentioned
    135 Post(s)
    Quoted
    418 Post(s)

    Default

    Close requested.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •