Home > Java > HangMan in Java

HangMan in Java

Here’s s simple version of HangMan, that i completed yesterday. It has a GameLogicEngine class containing its core rules. If any of you find any sort of suggestions to improve it than please do let me know by commenting the post…

The following class the HangManGUI.java is responsible for the GUI display logic and interfacing with players.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class HangManGUI extends JFrame implements ActionListener { 

//instance variables

private JMenuBar jMenuBar;

private JMenu helpMenu, exitMenu;

private JMenuItem aboutMenuItem;

private JPanel leftPanel, rightPanel, centerPanel;

private JButton[] abcButtons;

private JButton newWordButton;

private JLabel wordLabel, imageLabel;

public GameLogicEngine gle;

private static String[] abc = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

public static Character[] insertLetter;

private static String[] imgNames = {"imgs/hm_1.png", "imgs/hm_2.png", "imgs/hm_3.png", "imgs/hm_4.png", "imgs/hm_5.png", "imgs/hm_6.png", "imgs/hm_7.png", "imgs/hm_8.png", "imgs/hm_9.png", "imgs/hm_10.png"};

private int hangManState = 0;



//**class constructor**//


public HangManGUI() {

super("HangMan - Beta Version (0.0)");

this.setSize(400, 400);

this.setDefaultCloseOperation(HangManGUI.EXIT_ON_CLOSE);

this.setVisible(true);



//instantiate the JMenuBar and add it to the JFrame object

this.jMenuBar = new JMenuBar();

this.helpMenu = new JMenu("Help");

this.aboutMenuItem = new JMenuItem("About");

this.aboutMenuItem.addActionListener(this);

this.helpMenu.add(this.aboutMenuItem);

this.jMenuBar.add(this.helpMenu);


this.exitMenu = new JMenu("Exit");

this.exitMenu.addActionListener(this);

this.jMenuBar.add(this.exitMenu);

this.setJMenuBar(this.jMenuBar);

this.setLayout(new BorderLayout());


//instantiate the GameLogicEngine class

this.gle = new GameLogicEngine();


} 






//this method is responsible for painting all the components on the JFrame object

public void pasteComponents() { 

this.leftPanel = new JPanel();

this.leftPanel.setPreferredSize(new Dimension(120, 400));

this.leftPanel.setBackground(Color.pink);

this.add(this.leftPanel, BorderLayout.WEST);


//instantiate the JButton array

this.abcButtons = new JButton[26];

for(int i=0; i<26; i++) { 

this.abcButtons[i] = new JButton(HangManGUI.abc[i]);

this.abcButtons[i].addActionListener(this);

this.leftPanel.add(this.abcButtons[i]);


}


//instantiate the JButton instance "newWordButton"

this.newWordButton = new JButton("New Word");

this.newWordButton.addActionListener(this);

this.newWordButton.setFont(new Font("Times New Roman", Font.BOLD, 12));

this.add(newWordButton, BorderLayout.SOUTH);


//instantiate the JPanel rightPanel

this.rightPanel = new JPanel();
this.rightPanel.setPreferredSize(new Dimension(270, 400));
this.rightPanel.setBackground(Color.white);

this.add(this.rightPanel, BorderLayout.EAST);


//add image to the rightPanel object

this.imageLabel = new JLabel();

this.imageLabel.setIcon(new ImageIcon(HangManGUI.imgNames[0]));

this.rightPanel.add(this.imageLabel);


//instantiate the centerPanel

this.centerPanel = new JPanel();
this.centerPanel.setPreferredSize(new Dimension(40, 50));

//instantiate the wordLabel
this.wordLabel = new JLabel("         A word will appear here");
this.wordLabel.setFont(new Font("Courier New Bold", Font.BOLD, 17));

this.centerPanel.setLayout(new BorderLayout());
this.centerPanel.add(this.wordLabel, BorderLayout.CENTER);


this.add(this.centerPanel, BorderLayout.CENTER);

}




//a mthod responsible for replacing a new word on the GUI when the newWordButton is pressed

private void pasteNewWord(String word) { 

String displayWord = " ";

for(int i=0; i<word.length(); i++) { 

displayWord+=" _ ";

}

this.wordLabel.setText(displayWord);


}



//this method is responsible for the displaying of the correct word pressed by player

public void displayCorrectLetter() { 

String displayLetter = " ";

for(int i=0; i<HangManGUI.insertLetter.length; i++) { 

if(HangManGUI.insertLetter[i]!=null) {

displayLetter+= " "+HangManGUI.insertLetter[i].toString()+" ";

}
else { 

displayLetter+=" _ ";

}

}

this.wordLabel.setText(displayLetter);

}






//override actionPerformed()

public void actionPerformed(ActionEvent ev) { 


//check first for events from (A-Z) abcButtons

for(int i=0; i<26; i++) { 

if(ev.getSource()==this.abcButtons[i]) {

this.gle.presentWordPressed = this.abcButtons[i].getText();

System.out.println("You Pressed: "+this.gle.presentWordPressed);


//**problematic code possibly begins here

if(this.gle.evaluateDecision()==1) { 

System.out.println("Hello:");


this.displayCorrectLetter();


for(int j=0; j<HangManGUI.insertLetter.length; j++) { 

System.out.println(HangManGUI.insertLetter[j]);

} 

} 

else { 

System.out.println("I am else");

this.hangManState++;
 
this.imageLabel.setIcon(new ImageIcon(HangManGUI.imgNames[this.hangManState])); 

}


} 


} 







if(ev.getSource()==this.aboutMenuItem) { 

ApplicationDialog ad = new ApplicationDialog(this, "About");

ad.showAbout();

}

else { 


if(ev.getSource()==this.exitMenu) { System.exit(0); }

else { 

if(ev.getSource()==this.newWordButton) { 

String word = WordRepository.generateWord();

HangManGUI.insertLetter = new Character[word.length()];

this.gle.randomWordGenerated = word;

this.pasteNewWord(word);

this.newWordButton.setEnabled(false);

System.out.println("Random Word Generated is: "+ word);

}

}

}

}

}

The following class is basically a word repository for the HangMan and is responsible for the word generation at random.

import java.util.*;


public class WordRepository { 


//static variables

private static String[] words = {"FRUIT", "USMAN", "FISH", "WATER", "PAKISTAN", "PLANET", "CLOUDS", "COMPUTER", "VENUS", "OCEAN"};


//a method that generates a word at random

public static String generateWord() { 

//instantiate the Random class and invoke the nextInt() method to generate a randome number

Random ran = new Random();

int wordIndex = ran.nextInt(WordRepository.words.length);


String selectedWord = WordRepository.words[wordIndex];

return selectedWord;

}



}

This class the GameLogicEngine.java is particularly the most important one controlling and defining the game’s logic

/**
 * The core functionality of this class
 * is to embed the Basic Logic of HangMan.
 * It is kept final so it may not be extended 
 * and customized therefore.
*/


public final class GameLogicEngine { 

//instance variable

String randomWordGenerated;

String presentWordPressed;

private int matchingIndex;



// a method to evaluate the decision of player in the pressing of letters(A-Z) for
// filling the missing letters of the word displayed, this method returns a 1 for correcyt letter
//selection by user and a 0 for the incorrect

public int evaluateDecision() { 

int result=0;

if( this.checkLetterPresence() ) { 

for(int i=0; i<this.randomWordGenerated.length(); i++) { 

if(i==this.matchingIndex) { 

result = 1;

HangManGUI.insertLetter[i] = this.presentWordPressed.charAt(0);

}


}

}

else { 

result = 0;

}


return result;
} 







//a method to check weather the pressed letter is contained in the randomly generated word or not

private boolean checkLetterPresence() { 

boolean retBool;

int val = this.randomWordGenerated.indexOf(this.presentWordPressed);

if((val!=-1)&(val<=(this.randomWordGenerated.length()-1))) {

this.matchingIndex = val;

retBool = true;

}

else { 

retBool = false;

}

return retBool;

}


}

The following class is for presenting Application specific dialogs and is a custom version of the JDialog.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ApplicationDialog extends JDialog implements ActionListener { 

private JLabel aboutLabel;

private JButton okButton;




//**class constructor**//

public ApplicationDialog(JFrame ownerFrame, String title) { 

//invoke the parent class constructor

super(ownerFrame, true);

setTitle(title);

setSize(400, 400);

setLocation(270, 150);

setLayout(new FlowLayout());

}




///////below would be methods that are responsible for displaying content on the/////////////
//////JDialog object as per event requirememnts//////////////////////////////////

public void showAbout() {

add(new JLabel("          "));

aboutLabel = new JLabel(new ImageIcon("imgs/hello.gif"));

add(aboutLabel);

add(new JLabel("                                                                             "));

add(new JLabel("Software developed by:   Hassan Ali BS(CS) 6A"));



okButton = new JButton("OK");
okButton.addActionListener(this);

add(okButton);

setVisible(true);

}







//override actionPerformed()

public void actionPerformed(ActionEvent event) { 

if(event.getSource()==okButton) { 

this.dispose();

}


}


}


Last but not least this is the Driver for main:-)

public class Driver { 

public static void main(String[] args) { 

HangManGUI hg = new HangManGUI();

hg.pasteComponents();

}

}

You can make comments on the post directly at the page or can also mail me at malikhassan7@hotmail.com

_________________________

Advertisements
Categories: Java
  1. Amna
    July 22, 2010 at 1:54 pm

    Good Effort….Keep it up

  2. September 23, 2012 at 12:53 pm

    erm.. why i got a lot of errors in this codes?? 😦

    • September 24, 2012 at 5:54 am

      What kind of errors..? Mention the exceptions and i’ll tell you the reason. Probably images are not present at your end so it might be that. You have to place all the images at the path specified in the code.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: