Word Guessing game in Java Hi, i am little confused with my Java assignment. I n
ID: 647929 • Letter: W
Question
Word Guessing game in Java
Hi, i am little confused with my Java assignment. I need to build a program that will create a word guessing GUI.
Here are the reqiuerments:
You play the game by clicking on a letter button. If the letter you clicked is part of the hidden word then the letter (or letters) should be displayed, in the correct position, in the hidden word. When you press the I button, all three letters should appear in their correct position. Clicking a correct letter does not count against you, so correct letters should not increment the wrong guess counter. Whenever you click a letter you should disable it so that you won
Word Guessing game in Java Hi, i am little confused with my Java assignment. I need to build a program that will create a word guessing GUI. Here are the reqiuerments: You play the game by clicking on a letter button. If the letter you clicked is part of the hidden word then the letter (or letters) should be displayed, in the correct position, in the hidden word. When you press the I button, all three letters should appear in their correct position. Clicking a correct letter does not count against you, so correct letters should not increment the wrong guess counter. Whenever you click a letter you should disable it so that you wont accidently press it again. Notice the letter I is disabled below. Notice the letter I is disabled below since Ive already pressed it before. Clicking a wrong letter does increment the wrong guess counter. The user has clicked the letter A, which is part of the word, so the wrong guess counter is not incremented. Then the user presses the letter B. The letter B is not part of the word so the wrong guess counter is incremented. If the user wins the game you should print a congratulatory message, disable all of the letter buttons and display a Play Again button.Explanation / Answer
Program code:
import java.awt.Color;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.io.*;
public class GuessGame extends JPanel
{
File file;
String easy[];
Random randomGenerator = new Random();
int count=0;
private DashPanel panDashes = new DashPanel();
private String wtg;
private StringBuilder dashes = new StringBuilder();
private JFrame frmJavaHangman;
JButton btnNewGame = new JButton("Play Again");
JPanel jpan = new JPanel(new GridLayout(6, 5, 15, 15));
private JLabel hiddenWord=new JLabel("Hidden Word");
private JLabel triesLb=new JLabel();
int tries=10;
int wrongGuess=0;
private JLabel wrongs=new JLabel();
private JLabel wrongCount=new JLabel();
/**
* Launch the application.
*/
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
GuessGame window = new GuessGame();
window.frmJavaHangman.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public GuessGame() throws Exception
{
initialize();
}
private void initialize() throws Exception
{
frmJavaHangman = new JFrame();
frmJavaHangman.setResizable(false);
frmJavaHangman.setTitle("CSE 271 - Hangman");
frmJavaHangman.setAlwaysOnTop(true);
frmJavaHangman.setBounds(100, 100, 672, 643);
frmJavaHangman.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmJavaHangman.getContentPane().setLayout(null);
ButtonClick bc = new ButtonClick();
frmJavaHangman.getContentPane().setVisible(true);
frmJavaHangman.getContentPane().add(this);
hiddenWord.setFont(new Font("Comic Sans MS",Font.BOLD,20));
hiddenWord.setBounds(10, 10, 250, 30);
frmJavaHangman.getContentPane().add(hiddenWord);
btnNewGame.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
JButton btn;
for(Object o : frmJavaHangman.getContentPane().getComponents())
{
if(o instanceof JButton)
{
btn = (JButton)o;
if(btn.getText().length() == 1)
{
btn.setEnabled(true);
btn.setBackground(Color.yellow);
try
{
count=0;
setNewWord();
panDashes.repaint();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
});
btnNewGame.setBounds(400, 10, 150, 30);
btnNewGame.setFont(new Font("Comic Sans MS",Font.BOLD,20));
frmJavaHangman.getContentPane().add(btnNewGame);
panDashes.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panDashes.setBounds(18, 50, 537, 38);
frmJavaHangman.getContentPane().add(panDashes);
triesLb.setText("You have "+tries+" tries to guess to word");
triesLb.setAlignmentX(Component.CENTER_ALIGNMENT);
triesLb.setBounds(18,90,537, 38 );
triesLb.setFont(new Font("Comic Sans MS",Font.BOLD,20));
triesLb.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
frmJavaHangman.getContentPane().add(triesLb);
wrongs.setText("Number of wrong guesses ");
wrongs.setAlignmentX(Component.CENTER_ALIGNMENT);
wrongs.setBounds(18,150,540, 38 );
wrongs.setFont(new Font("Comic Sans MS",Font.BOLD,20));
frmJavaHangman.getContentPane().add(wrongs);
wrongCount.setText(""+wrongGuess);
wrongCount.setAlignmentX(Component.CENTER_ALIGNMENT);
wrongCount.setBounds(300,150,30, 38 );
wrongCount.setFont(new Font("Comic Sans MS",Font.BOLD,20));
wrongCount.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
frmJavaHangman.getContentPane().add(wrongCount);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
// Create all A-Z buttons
jpan.setBounds(18, 200, 550, 300);
jpan.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
for(int i = 0; i < 26; i++)
{
JButton btn = new JButton("" + (char)(65 + i));
btn.setFont(new Font("Comic Sans MS",Font.BOLD,20));
btn.setBackground(Color.yellow);
btn.addActionListener(bc);
jpan.add(btn);
frmJavaHangman.getContentPane().add(jpan);
}
setNewWord();
}
public void paint(Graphics g)
{
super.paint(g);
// Now repaint the dashes JPanel
panDashes.repaint();
}
private void setNewWord() throws FileNotFoundException
{
wtg=getWord();
wtg = wtg.toUpperCase();
dashes = new StringBuilder(new String(new char[wtg.length()]).replace("", "*"));
}
private String getWord() throws FileNotFoundException
{
int i=0;
int num=0;
file=new File("words.txt");
Scanner in=new Scanner(file);
if(file.exists())
{
num=in.nextInt();
easy=new String[num];
while(in.hasNextLine())
{
easy[i]=in.next();
i++;
}
}
return easy[randomGenerator.nextInt(num)];
}
private void showDashes()
{
System.out.println(dashes.toString());
}
// Method that updates the dashes string with a guessed letter
private boolean guessLetter(char letter)
{
boolean ret = false;
for(int i = 0; i < wtg.length(); i++)
if(wtg.charAt(i) == letter)
{
panDashes.repaint();
dashes.replace(i, i+1, ""+letter);
ret = true;
}
showDashes();
return ret;
}
private boolean checkForWin()
{
// If we search the dashes string and don't find a dash then game over
return dashes.indexOf("*") == -1;
}
private void gameOver()
{
JButton btn;
// Look at each object on the frame
for(Object o : frmJavaHangman.getContentPane().getComponents())
// Found a JButton
if(o instanceof JButton)
{
btn = (JButton)o;
// If the button has only 1 character then it's a letter so disable it.
if(btn.getText().length() == 1)
btn.setEnabled(false);
if(count==10)
btn.setEnabled(false);
}
}
// A simple class to handle the dashes panel
private class DashPanel extends JPanel
{
public void paintComponent(Graphics g)
{
int x = getWidth();
int y = getHeight();
super.paintComponent(g);
Font f = new Font("Courier New", 1, getHeight());
g.setFont(f);
FontMetrics metrics = getFontMetrics(f);
int h = metrics.getHeight();
int w = metrics.stringWidth(dashes.toString());
g.drawString(dashes.toString(), getWidth()/2 - w/2, getHeight() - h/4);
}
}
// A class to handle the clicks of the letters
private class ButtonClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
boolean flag=guessLetter(btn.getText().charAt(0));
if (flag)
btn.setBackground(Color.green );
else
{
btn.setBackground(Color.red );
++count;
tries--;
++wrongGuess;
triesLb.setText("You have "+tries+" tries to guess to word");
wrongCount.setText(""+wrongGuess);
}
btn.setEnabled(false);
repaint();
if (checkForWin())
gameOver();
if(count>10)
{
gameOver();
}
}
}
}
Note:
Please attach a text file that contains the data as follows:
First line is number of words in the file.
words.txt file.
20
bulbusaur
ivysaur
charmander
charmeleon
charizard
squirtle
wartotle
blastoise
caterpie
metapod
butterfree
weedle
kakuna
beedrill
pidgee
pidgeotto
pidgeot
rattata
raticate
spearow
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.