Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone write a hangman game in java with a very simple G.U.I? The game woul

ID: 3843394 • Letter: C

Question

Can someone write a hangman game in java with a very simple G.U.I? The game would give the user two options. The first would be if the user is by hmiself then the user would choose option one and the game would pick a random word from a array and have the user guess random letters just like in hangman. The second option would be for two players and would allow the user to enter the word he wanted to guess. In both game modes the game would print out the incorrect guesses made, what the guesses where and it would print out the number of incorrect guesses left before they lost the game.

Thank you

Explanation / Answer

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication6;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

/**
*
* @author Rashmi Tiwari
*/

public class HangmanGame {
static String[] listOfWords;
static String secretWord;
static Set<Character> alphabet;
static Set<Character> guessedLetter; // letters the user has guessed
static boolean[] revealedLetter; // determines if the letter should be revealed or not
static int guessesRemaining;

public static void main(String[] args){
HangmanGame hangman = new HangmanGame();
hangman.createAlphabetSet();
Scanner sc=new Scanner(System.in);
System.out.println("You have two option to choose");
System.out.println("Enter 1 for single player");
System.out.println("Enter 2 for two player");
int ch=sc.nextInt();
switch(ch){
case 1:{
hangman.readFile("words.txt");
HangmanGameGUI.buildGUI();
setUpGame();
}
break;
case 2:
{
hangman.readFile("words.txt");
HangmanGameGUI.buildGUI();
setUpGame();
}
break;
default:
System.out.println("Invalid choice");
}
  
  
}

// checkIfWon - sees if the user has won the game
static boolean checkIfWon(){
for(boolean isLetterShown : revealedLetter){
if(!isLetterShown)
return false;
}
return true;
}

// checkUserGuess - get input from the user
static boolean checkUserGuess(String l){
if(l.length() == 1 && !guessedLetter.contains(l.charAt(0)) && alphabet.contains(l.charAt(0))) {
HangmanGameGUI.setText(null);
guessedLetter.add(l.charAt(0));
return true;
}else{
Toolkit.getDefaultToolkit().beep();
}
return false;
}

// chooseSecretWord - selects a word
private static String chooseSecretWord(String[] listOfWords){
return listOfWords[(int)(Math.random() * listOfWords.length)];
}

// createAlphabetSet - Creates the alphabet set that's used to ensure that the user's guess not a number nor a special character
private void createAlphabetSet(){
alphabet = new HashSet<Character>(26);
for(Character c = 'a'; c<='z'; c++){
alphabet.add(c);
}
}

// loseSequence - when the the user runs out of guesses
static void loseSequence(){
for(int i = 0; i < revealedLetter.length; i++){
revealedLetter[i] = true;
}
HangmanGameGUI.drawSecretWord();
playAgain("Tough luck. The secret word was " + secretWord + ". Would you like to play another game of hangman?");
}

// playAgain - Allows the user to play another game of hangman
private static void playAgain(String message){
int ans = HangmanGameGUI.playAgainDialog(message);
if(ans == JOptionPane.YES_OPTION){
setUpGame();
}else{
System.exit(0);
}
}

// readFile - read in listOfWords
private String[] readFile(String loc){
BufferedReader input = null;
try{
input = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(loc)));
listOfWords = input.readLine().split(" ");
}catch(IOException ioException) {
ioException.printStackTrace();
}finally{
try {
if (input != null) input.close();
}catch(IOException ioEx){
ioEx.printStackTrace();
}
}
return listOfWords;
}

// setUpGame - sets up the variables appropriately
private static void setUpGame(){
guessesRemaining = 5;
secretWord = chooseSecretWord(listOfWords);
revealedLetter = new boolean[secretWord.length()];
Arrays.fill(revealedLetter, false);
guessedLetter = new HashSet<Character>(26); // 26 letters in alphabet

HangmanGameGUI.drawSecretWord();
HangmanGameGUI.drawLettersGuessed();
HangmanGameGUI.drawGuessesRemaining();
}

// updateSecretWord - updates which letters of the secret word have been revealed
static void updateSecretWord(String l){
List<Integer> changeBool = new ArrayList<Integer>();

if(secretWord.contains(l)){
// Searches through secretWord & notes down all letters that equal the user's guess
for(int i=0; i<secretWord.length(); i++){
if(secretWord.charAt(i) == l.charAt(0))
changeBool.add(i);
}

// Changes the boolean value for those letters @ their corresponding indexes
for(Integer idx : changeBool)
revealedLetter[idx] = true;
}else{
guessesRemaining--;
HangmanGameGUI.drawGuessesRemaining();
}
}

// winSequence - when the user has correctly guessed the secret word
static void winSequence(){
playAgain("Well done! You guessed " + secretWord + " with " + guessesRemaining + " guesses left! " +
"Would you like to play another game of hangman?");
}

}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication6;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
*
* @author Rashmi Tiwari
*/

/**
*
* @author Rashmi Tiwari
*/
public class HangmanGameGUI {

// GUI
static JFrame frame;
static JTextField textField;
static JLabel guessesRemainingLabel;
static JLabel lettersGuessedLabel;
static JLabel secretWordLabel;

// buildGUI - builds the GUI
static void buildGUI(){
SwingUtilities.invokeLater(
new Runnable(){
@Override
public void run(){
frame = new JFrame("Hangman");

// JLabels
guessesRemainingLabel = new JLabel("Guesses remaining: " + String.valueOf(HangmanGame.guessesRemaining));
lettersGuessedLabel = new JLabel("Already guessed: ");
secretWordLabel = new JLabel();

// TextField & checkButton
textField = new JTextField();
JButton checkButton = new JButton("Guess");
GuessListener guessListener = new GuessListener();
checkButton.addActionListener(guessListener);
textField.addActionListener(guessListener);

// Panel for all the labels
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.PAGE_AXIS));
labelPanel.add(guessesRemainingLabel);
labelPanel.add(lettersGuessedLabel);
labelPanel.add(secretWordLabel);

// User panel
JPanel userPanel = new JPanel(new BorderLayout());
userPanel.add(BorderLayout.CENTER, textField);
userPanel.add(BorderLayout.EAST, checkButton);
labelPanel.add(userPanel);

// Add everything to frame
frame.add(BorderLayout.CENTER, labelPanel);

frame.setSize(250, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
);
}

// drawGuessesRemaining - Outputs the guesses remaining
static void drawGuessesRemaining(){
final String guessesMessage = "Guesses remaining: " + String.valueOf(HangmanGame.guessesRemaining);
SwingUtilities.invokeLater(
new Runnable(){
@Override
public void run(){
guessesRemainingLabel.setText(guessesMessage);
guessesRemainingLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
}
}
);
}

// drawLettersGuessed - Outputs the letters guessed
static void drawLettersGuessed(){
StringBuilder lettersBuilder = new StringBuilder();
for (Character el : HangmanGame.guessedLetter) {
String s = el + " ";
lettersBuilder.append(s);
}

final String letters = lettersBuilder.toString();
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
lettersGuessedLabel.setText("Already guessed: " + letters);
}
}
);
}

// drawSecretWord - draws the secret word with dashes & etc for user to use to guess the word with
static void drawSecretWord(){
StringBuilder word = new StringBuilder();
for(int i=0; i<HangmanGame.revealedLetter.length; i++){

if (HangmanGame.revealedLetter[i]) {
String s = HangmanGame.secretWord.charAt(i) + " ";
word.append(s);
} else {
word.append("_ ");
}
}

final String w = word.toString();
SwingUtilities.invokeLater(
new Runnable(){
@Override
public void run() {
secretWordLabel.setText(w);
}
}
);
}

//playAgainDialog - shows the confirm w
static int playAgainDialog(String m){
return JOptionPane.showConfirmDialog(frame, m, "Play again?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
}


// GETTERS
private static String getText(){
return textField.getText();
}

// SETTERS
static void setText(final String t){
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
textField.setText(t);
}
}
);
}


// ActionListener
private static class GuessListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev){
String guess = getText();

if(HangmanGame.checkUserGuess(guess)) {
HangmanGame.updateSecretWord(guess);
drawSecretWord();

if(HangmanGame.guessedLetter.size() != 0) // No letters have been guessed by the user at the beginning
drawLettersGuessed();

// Checks if the user has won or lost
if (HangmanGame.checkIfWon())
HangmanGame.winSequence();
else if (HangmanGame.guessesRemaining == 0)
HangmanGame.loseSequence();
}
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote