Hangman game with GUI interface

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 19350 Views - Last Post: 20 January 2011 - 04:17 PM Rate Topic: -----

#1 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Hangman game with GUI interface

Posted 13 January 2011 - 11:10 AM

I was never very good with java and on top of that I haven't done anything with it in a while so I've just been banging my face against the keyboard for a while now trying to get something somewhat functional, but to no avail. I have two classes within my hangman package, one is with all the gui interface and one is with all the game functionality(gui and hangman are the two class names). I need to link the buttons/labels to the methods in my hangman class. I've been reading through http://download.orac...ents/index.html and http://www.dreaminco...c-gui-concepts/, but I'm still kinda lost on where to go next. I know I need to setup the actionlisteners, but I guess I'm unsure where and how to do it. For instance I have jbutton1 (start new game) that i need to run my playGame() method on mouseclick.

This post has been edited by OmniSmurfZ: 13 January 2011 - 11:11 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Hangman game with GUI interface

#2 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Hangman game with GUI interface

Posted 13 January 2011 - 11:13 AM

Try this tutorial about JButtons first.
http://download.orac...nts/button.html
If you have any other issues, feel free to post again :)
Was This Post Helpful? 0
  • +
  • -

#3 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 13 January 2011 - 12:38 PM

Well my main issue is the fact that they're both within two separate classes, none of the tutorial stuff talks about that.
Was This Post Helpful? 0
  • +
  • -

#4 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Hangman game with GUI interface

Posted 13 January 2011 - 01:26 PM

Post your code..
as pbl would say in that case:
we are the blinds leading the blind :)
Was This Post Helpful? 1
  • +
  • -

#5 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 13 January 2011 - 02:51 PM

Well as of no it makes absolutely no sense, but thats because i just keep trying different things... I'm using netbeans and thats why gui.java looks the way it does (add JFrame form function of netbeans).

import Gui;

import java.io.*;
import java.awt.*;
import java.util.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

package hangman;


public class Hangman {
    static final int MAXGUESS = 8; //max guesses per word
    static final int MAXLETTER = 'z' - 'a' + 1; //number of letters in alphabet

    static final String[] WORDS = {"apple", "banana", "cat", "dog",
    "elephant", "fish", "giraffe", "hippopotamus", "ice cream",
"jelly",
    "kangaroo", "lion", "monkey", "noodles", "octopus", "parrot",
"queen",
    "rabbit", "sun", "tree", "umbrella", "van", "window", "x-ray",
"yellow",
    "zebra"};

    //button stuff
    private JButton jbutton1, jbutton2, jbutton3;
    private StartNewHandler snHandler;
    private SolveHandler soHandler;

    //handlers and actionlisteners
    jbutton1 = new JButton("Start New");
    snHandler = new StartNewHandler();
    jbutton1.addActionListener(snHandler);
    jbutton2 = new JButton("Solve");
    soHandler = new SolveHandler();
    jbutton2.addActionListener(soHandler);

    public static void main(String[] args) {
      boolean again;        // true while we play another game
      String answer;        // users input
      System.out.println("\nThis is the word guessing game called Hangman.");
      System.out.println("The computer will pick a word and you must try to");
      System.out.println("guess the letters in the word. If you guess the");
      System.out.println("word with less than " + MAXGUESS + " mistakes, then you win!");
      do
      {
          playGame();       //play one game of Hangman
          System.out.println("\nWould you like to play another game? (YES OR NO)");
          answer = Keyboard.readString();
          if (answer.equalsIgnoreCase("yes"))
              again = true;
          else if (answer.equalsIgnoreCase("mo"))
              again = false;
          else
          {
              again = false;
              System.out.println("Your answer \"" + answer + "\" should be YES or NO.");
          }
      }
      while (again);
      System.out.println("\nThank you for playing Hangman!");
    }  //main end

    static void playGame()
    {
        boolean[] already;  //if user already guessed these letters
        char c;             // temporary variable for a character
        boolean[] display;  //if we display each letter in word
        int found;          //how many times we find user's guess
        int i;              //temporary variable for index loop
        char inputChar;     // users input (as one character)
        String inputString;     //users input (as a string)
        int length;     //length of our random word
        int letters;        //actual letters in word (not " " or "-")
        int mistakes;       //number of mistakes
        boolean playing;        //true while we are playing game
        String word;        //our random word from WORDS list
        mistakes = 0;       //start with no mistakes

        //Pick a random word from WORDS list.
        word = WORDS [(int)(Math.random() * WORDS.length)];
//        System.out.println("debug: word = ' " + word + "'");
        length = word.length();     //get length of random word

        //Create a display array to decide if we display a letter in the word

        display = new boolean[length];
        letters = 0;        //actual letters in word
        for (i=0; i < length; i ++)
        {
            c = word.charAt(i);     //get one char from word
            if ((c >= 'a') && (c <= 'z'))
            {
                display[i] = false; //hide all letters
                letters ++;     //count number of letters found
            }
            else
                display[i] = true;      //not a letter: show special characters
        }
        System.out.print("\nI am thinking of a word.   ");
        if (letters == 1)
            System.out.println("The word has one letter.");
        else
            System.out.println("The word has " + letters + " letters.");

        //make a boolean array to remember which letters the user has guessed.
        already = new boolean[MAXLETTER];
        for (i = 0; i < MAXLETTER; i ++)
        already[i] = false;

        //ask the user for his guess in a loop.
        playing = true;     //we are playing the game
        while (playing)
        {
            //display the word, with unkown letters marked by *
            System.out.print("\nThe word is:");
            for (i = 0; i < length; i ++)
            {
                System.out.print(" ");      //put a space between letters
                if (display[i])
                    System.out.print(word.charAt(i));
                else
                    System.out.print("*");
            }

            System.out.print("/n What is your guess?   ");
            if ((MAXGUESS - mistakes) <= 1)
                System.out.println("This is your last guess!");
            else
                System.out.println("You have " + (MAXGUESS - mistakes) + "guesses remaining.");

            inputString = Keyboard.readString();
            inputString = inputString.trim();   //remove leading/trailing spaces
            inputString = inputString.toLowerCase(); //convert 'A' to 'a'

            if (inputString.length() == length)
            {
                //user is guessing the whole word
                if (word.equals(inputString))
                {
                    System.out.println("Yes, the word is \"" + word + "\"!");
                    printMistakes(mistakes);
                    playing = false;
                }
                else
                {
                    System.out.println("Sorry, the word is not \"" + inputString + "\".");
                }
            }
            else if (inputString.length() != 1)
            {
                System.out.println("Your guess \"" + inputString + "\" must be one letter or the entire word.");
            }
            else
            {
                //user is guessing one letter
                inputChar = inputString.charAt(0);
                if ((inputChar < 'a') || (inputChar > 'z'))
                {
                    //users input is not a letter
                    System.out.println("Your guess \"" + inputChar + "\" must be a letter from A to Z, or the entire word.");
                }
                else if (already[inputChar - 'a'])
                {
                    //user already guessed this letter. dont count as a mistake.
                    System.out.print("You have already guessed the following letters:");
                    for (i = 0; i < MAXLETTER; i ++)
                        if (already[i])
                            System.out.print(" " + (char)(i + 'a'));
                    System.out.println();
                }
                else
                {
                    //count how many times this letter is in the word, and change the variables that control the display
                    already[inputChar - 'a'] = true;    //this letter is now used
                    found = 0;      //clear matching letters found
                    for (i = 0; i < length; i ++)
                        if (word.charAt(i) == inputChar)
                        {
                            display[i] = true;
                            found ++;
                        }
                    if (found <= 0)
                    {
                        System.out.println("Sorry, the letter \"" + inputChar + "\" is not in the word.");
                        mistakes ++;
                    }
                    else
                    {
                        //tell the user how many letters were found. Make a special grammar case for the number one
                        if (found == 1)
                            System.out.println("Yes, there is one letter \"" + inputChar + "\" in the word.");
                        //check if the whole word has now been guessed.
                        playing = false;          //assume we are finished
                        for (i = 0; i < length; i ++)
                            playing = playing || !display[i];
                        if (!playing)
                        {
                            System.out.println("You found all the letters in the word \"" + word + "\".");
                            printMistakes(mistakes);
                        }
                    }
                }
            }
            if (mistakes >= MAXGUESS)
            {
                System.out.println("The word was \"" + word + "\".");
                playing = false;
            }
        }
    }   //end of playGame()

    static void printMistakes(int n)
    {
        if (n <= 0)
            System.out.println("You didn't make any mistakes. Excellent!");
        else if (n == 1)
            System.out.println("You made only one mistake. Great!");
        else
            System.out.println("You made only " + n + " mistakes. Good!");
    }
}                     //end of class




package hangman;

/**
 *
 * @author Chris
 */
public class Gui extends javax.swing.JFrame {

    /** Creates new form Gui */
    public Gui() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Start New");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Solve");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Exit");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setText("Current Trial:");

        jLabel2.setText("Current Score:");

        jButton4.setText("Home");

        jLabel3.setText("Hangman Classic");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(435, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(435, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(435, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton4)
                                .addGap(76, 76, 76)
                                .addComponent(jLabel1)))
                        .addGap(7, 7, 7))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton4)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(53, 53, 53)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      
setDefaultCloseOperation(EXIT_ON_CLOSE);
    }                                     

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {



    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Gui().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration

}


This post has been edited by OmniSmurfZ: 13 January 2011 - 02:51 PM

Was This Post Helpful? 0
  • +
  • -

#6 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 497
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Re: Hangman game with GUI interface

Posted 13 January 2011 - 04:21 PM

It's not good using a GUI builder built into an IDE like Netbeans since it provides unmaintainable code. Have a look at this which explains how to use action listeners.
Was This Post Helpful? 3
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Hangman game with GUI interface

Posted 13 January 2011 - 08:24 PM

And congratulations for your comments. You won't be able to re-read your own code in 2 weeks.

We will be glad to help you with YOUR code not with code generated by a GUI generater that you do not handle correctly. Checking code is easy, guessing where and when you clicked and selected a good option at the good place is impossible to do.
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10785
  • View blog
  • Posts: 40,160
  • Joined: 27-December 08

Re: Hangman game with GUI interface

Posted 13 January 2011 - 10:07 PM

Also, not good practice to use so much static or to manage parallel arrays. Instead, manage a Map<Character, Boolean> to determine if a letter has been guessed.
boolean[] already;  //if user already guessed these letters  
boolean[] display; 


Was This Post Helpful? 1
  • +
  • -

#9 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 14 January 2011 - 09:03 AM

To the two posts above mine, yes I realize how shitty most that stuff is, that is why I prefaced it with that statement^^^. Also some of that isn't mine and was stuff provided by our professor and yes I do realize how confusing his coding was and how he did it, probably part of the reason why I'm having so much trouble with this. Seems like I should just start from scratch because from every angle this program is fail.
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Hangman game with GUI interface

Posted 14 January 2011 - 07:47 PM

View PostOmniSmurfZ, on 14 January 2011 - 10:03 AM, said:

Seems like I should just start from scratch because from every angle this program is fail.

That would be the best approach :)
Was This Post Helpful? 0
  • +
  • -

#11 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 15 January 2011 - 11:52 AM

So I'm starting over and I'm following http://www.dreaminco...c-gui-concepts/ this guide to setup the main interface and stuff of the game, I'm stuck at the end pretty much though.

public static void main(String[] args)
    {
        RectangleProgram rectObj = new RectangleProgram();
    }



When I put this into my program it tells me that I can't use the 'static' part of that statement, if I don't have the static it tells me variable rectObj is not used, but with that tut it doesn't have rectObj in any other spot.

This post has been edited by OmniSmurfZ: 15 January 2011 - 11:54 AM

Was This Post Helpful? 0
  • +
  • -

#12 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 17 January 2011 - 09:07 AM

I've just been working on the game part as well, but for the actually visualization I haven't changed much, but still can't get anything to show up.

public class Gui extends JFrame
{
    private static final int WIDTH = 700;
    private static final int HEIGHT = 500;
    
    private JLabel ctL, ctsL, csL, cssL;
    private JButton newgameB, exitB, solveB, homeB;

    //button handlers
    private NewGameBH ngHandler;
    private ExitBH eHandler;
    private SolveBH sHandler;


    public Gui()
    {
        //Jframe main stuff
        setTitle("Hangman Classic");
        setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //instantiate buttons & labels
        newgameB = new JButton("Start New");
        exitB = new JButton("Exit");
        solveB = new JButton("Solve");
        homeB = new JButton("Home");
        ctL = new JLabel("Current Trial: ", SwingConstants.RIGHT);
        ctsL = new JLabel("0", SwingConstants.RIGHT);
        csL = new JLabel("Current Score: ", SwingConstants.RIGHT);
        cssL = new JLabel("0", SwingConstants.RIGHT);

        //specify handlers and add actionlisteners
        newgameB = new JButton("Start New");
        ngHandler = new NewGameBH();
        newgameB.addActionListener(ngHandler);
        exitB = new JButton("Start New");
        eHandler = new ExitBH();
        exitB.addActionListener(eHandler);
        solveB = new JButton("Start New");
        sHandler = new SolveBH();
        solveB.addActionListener(sHandler);

        //Get the content pane & setup the layout
        Container pane = getContentPane();
        pane.setLayout(new GridLayout(5, 3));
        //Add things to the pane in the order you want them to appear (left to right, top to bottom)
        pane.add(homeB);
        pane.add(ctL);
        pane.add(ctsL);
        pane.add(csL);
        pane.add(cssL);
        pane.add(newgameB);
        pane.add(solveB);
        pane.add(exitB);

  }
    public void main(String[] args)
    {
        Gui rectObj = new Gui();
    }

    //exit button action
    public class ExitBH implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    //solve button action
    public class SolveBH implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
        {

        }
    }

    //start new button action
    public class NewGameBH implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
        {

        }
    }
  }


Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10785
  • View blog
  • Posts: 40,160
  • Joined: 27-December 08

Re: Hangman game with GUI interface

Posted 17 January 2011 - 09:59 AM

You should be getting an error that is telling you it can't find the main() method. Note that the main() method must be static. You have:
public void main(String[] args)


Was This Post Helpful? 0
  • +
  • -

#14 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 17 January 2011 - 10:51 AM

I know this, it was doing that, but my post right above the last one...

Quote

"So I'm starting over and I'm following http://www.dreaminco...c-gui-concepts/ this guide to setup the main interface and stuff of the game, I'm stuck at the end pretty much though.


public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}


When I put this into my program it tells me that I can't use the 'static' part of that statement, if I don't have the static it tells me variable rectObj is not used, but with that tut it doesn't have rectObj in any other spot.


Or it tells me its a non-static variable and cannot be recognized from a static context.

This post has been edited by OmniSmurfZ: 17 January 2011 - 10:57 AM

Was This Post Helpful? 0
  • +
  • -

#15 OmniSmurfZ  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-February 10

Re: Hangman game with GUI interface

Posted 17 January 2011 - 11:09 AM

Not allowing multiple edits ftl =(. Sorry if that sounded pissy, nothing towards you guys, i've just been working on this for my entire weekend basically and not getting any where so I'm just frustrated with it.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2