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

Create in Java a GUI for the Hangman game. The game is played between the comput

ID: 3833396 • Letter: C

Question

Create in Java a GUI for the Hangman game. The game is played between the computer and one player. The player needs to guess the correct word by guessing a single character each time.


The GUI should have the following:

Words read from a file in place of being hardwired into the array

Read a file in that has all the words stored as one word per line, Store each word locally

All 26 alphabets should be displayed initially
After each guess, the guessed alphabet is removed from the display, so that the player knows that the alphabets remaining on the screen have not been used yet.
One button to restart the game
Another button to begin a new game
One field to display score
One field that shows the word in terms of blanks (dashes). These blanks should be populated with the right alphabet after each correct guess.

A GUI with Stick Figure instead of the “number of incorrect guesses” field that builds up based on each incorrect guess.

A timer function that ends the game after a certain period of time.

Alphabet Selection – By entering the alphabet or clicking on an alphabet
Alphabet is entered into a textfield by the player and press a button called “Guess”. This should notify the program that a new guess has been made
OR
All the alphabets are displayed as buttons and the player selects an alphabet by clicking on the appropriate button. The button click should inform the program that a new guess has been made.

If the player correctly guesses the word, the game should notify the player that they have won

Example:

NEW RESTART A B C D E F G H I J K L M N O P Q R S T U V Time: seconds left y 10 Score:

Explanation / Answer

Hangman.java

package Chegg;


import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
* A GUI version of the game of Hangman. The user tries to guess letters in
* a secret word, and loses after 7 guesses that are not in the word. The
* user guesses a letter by clicking a button whose text is that letter.
*/
public class Hangman extends JPanel {
  
   private Display display; // The central panel of the GUI, where things are drawn
  
   private ArrayList<JButton> alphabetButtons = new ArrayList<JButton>(); // 26 buttons, with lables "A", "B", ..., "Z"
   private JButton nextButton; // A button the user can click after one game ends to go on to the next word.
   private JButton giveUpButton; // A button that the user can click during a game to give up and end the game.
  
   private String message; // A message that is drawn in the Display.
   private WordList wordlist; // An object holding the list of possible words that can be used in the game.
   private String word; // The current secret word.
   private String guesses; // A string containing all the letters that the user has guessed so far.
   private boolean gameOver; // False when a game is in progress, true when a game has ended and a new one not yet begun.
   private int badGuesses; // The number of incorrect letters that the user has guessed in the current game.
  
   /**
   * This class defines a listener that will respond to the events that occur
   * when the user clicks any of the buttons in the button. The buttons are
   * labeled "Next word", "Give up", "Quit", "A", "B", "C", ..., "Z".
   */
   private class ButtonHandler implements ActionListener {
       public void actionPerformed( ActionEvent evt ) {
           JButton whichButton = (JButton)evt.getSource(); // The button that the user clicked.
           String cmd = evt.getActionCommand(); // The test from the button that the user clicked.
           if (cmd.equals("Quit")) { // Respond to Quit button by ending the program.
               System.exit(0);
           }
           else {
               message = "The command is " + cmd;
           }
           display.repaint(); // Causes the display to be redrawn, to show any changes made in this method.
       }
   }
  
   /**
   * This class defines the panel that occupies the large central area in the
   * main panel. The paintComponent() method in this class is responsible for
   * drawing the content of that panel. It shows everything that that the user
   * is supposed to see, based on the current values of all the instance variables.
   */
   private class Display extends JPanel {
       Display() {
           setPreferredSize(new Dimension(620,420));
           setBackground( new Color(250, 230, 180) );
           setFont( new Font("Serif", Font.BOLD, 20) );
       }
       protected void paintComponent(Graphics g) {
           super.paintComponent(g);
           ((Graphics2D)g).setStroke(new BasicStroke(3));
           if (message != null) {
               g.setColor(Color.RED);
               g.drawString(message, 30, 40);
           }
       }
   }
  
   /**
   * The constructor that creates the main panel, which is represented
   * by this class. It makes all the buttons and subpanels and adds
   * them to the main panel.
   */
   public Hangman() {
      
       ButtonHandler buttonHandler = new ButtonHandler(); // The ActionListener that will respond to button clicks.
      
       /* Create the subpanels and add them to the main panel.
       */
      
       display = new Display(); // The display panel that fills the large central area of the main panel.
       JPanel bottom = new JPanel(); // The small panel on the bottom edge of the main panel.

       setLayout(new BorderLayout(3,3)); // Use a BorderLayout layout manager on the main panel.
       add(display, BorderLayout.CENTER); // Put display in the central position in the "CENTER" position.
       add(bottom, BorderLayout.SOUTH); // Put bottom in the "SOUTH" position of the layout.

       /* Create three buttons, register the ActionListener to respond to clicks on the
       * buttons, and add them to the bottom panel.
       */
      
       nextButton = new JButton("Next word");
       nextButton.addActionListener(buttonHandler);
       bottom.add(nextButton);
      
       giveUpButton = new JButton("Give up");
       giveUpButton.addActionListener(buttonHandler);
       bottom.add(giveUpButton);
      
       JButton quit = new JButton("Quit");
       quit.addActionListener(buttonHandler);
       bottom.add(quit);
      
       /* Make the main panel a little prettier
       */

       setBackground( new Color(100,0,0) );
       setBorder(BorderFactory.createLineBorder(new Color(100,0,0), 3));
      
       /* Get the list of possible secret words from the resource file named "wordlist.txt".
       */

       wordlist = new WordList("H:/wordlist.txt");
      
       /* Start the first game.
       */
      
       startGame();
      
   } // end constructor
  
   /**
   * This method should be called any time a new game starts. It picks a new
   * secret word, initializes all the variables that record the state of the
   * game, and sets the enabled/disabled state of all the buttons.
   */
   private void startGame() {
       gameOver = false;
       guesses = "";
       badGuesses = 0;
       nextButton.setEnabled(false);
       for (int i = 0; i < alphabetButtons.size(); i++) {
           alphabetButtons.get(i).setEnabled(true);
       }
       giveUpButton.setEnabled(true);
       int index = (int)(Math.random()*wordlist.getWordCount());
       word = wordlist.removeWord(index);
       word = word.toUpperCase();
       message = "The word has " + word.length() + " letters. Let's play Hangman!";
   }
  
   /**
   * This method can be called to test whether the user has guessed all the letters
   * in the current secret word. That would mean the user has won the game.
   */
   private boolean wordIsComplete() {
       for (int i = 0; i < word.length(); i++) {
           char ch = word.charAt(i);
           if ( guesses.indexOf(ch) == -1 ) {
               return false;
           }
       }
       return true;
   }
  
   /**
   * This main program makes it possible to run this class as an application. The main routine
   * creates a window, sets it to contain a panel of type Hangman, and shows the window in the
   * center of the screen.
   */
   public static void main(String[] args) {
       JFrame window = new JFrame("Hangman"); // The window, with "Hangman" in the title bar.
       Hangman panel = new Hangman(); // The main panel for the window.
       window.setContentPane(panel); // Set the main panel to be the content of the window
       window.pack(); // Set the size of the window based on the preferred sizes of what it contains.
       window.setResizable(false); // Don't let the user resize the window.
       window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // End the program if the user closes the window.
       Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // The width/height of the screen.
       window.setLocation( (screen.width - window.getWidth())/2,
               (screen.height - window.getHeight())/2 ); // Position window in the center of screen.
       window.setVisible(true); // Make the window visible on the screen.
   }

}

WordList.java

package Chegg;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
* An object of type WordList reads a list of words from a resource file that is
* part of the same program and makes the words available.
*/
public class WordList {

   private ArrayList<String> words; // the list of words.

   /**
   * Create a list of words by reading from a resource file.
   *
   * @param wordlistFileName
   * the path to the resource file in the program.
   * @throws IllegalArgumentException
   * if words can't be read from the resource file.
   */
   public WordList(String wordlistFileName) {
       words = new ArrayList<String>();
       try {
           Scanner in;
           in = new Scanner(getClass().getClassLoader().getResource(wordlistFileName).openStream());
           while (in.hasNextLine()) {
               String line = in.nextLine().trim();
               if (line.length() > 0)
                   words.add(line);
           }
           if (words.size() == 0)
               throw new IllegalArgumentException("Nothing was found in the file " + wordlistFileName);
           System.out.println(words.size() + " words read from " + wordlistFileName);
       } catch (IOException e) {
           throw new IllegalArgumentException("Can't read list of words from " + wordlistFileName);
       }
   }

   /**
   * Returns the number of words in the list.
   */
   public int getWordCount() {
       return words.size();
   }

   /**
   * Returns a specified word from the list.
   *
   * @param index
   * the position of the word in the list, with positions numbered
   * from 0 to getWordCount() - 1.
   * @throws IndexOutOfBoundsException
   * if index is not in the range 0 to getWordCount() - 1.
   */
   public String getWord(int index) {
       return words.get(index);
   }

   /**
   * Returns a specified word from the list, and removes that word from the
   * list so it can't be fetched again. The size of the list decreases by one.
   *
   * @param index
   * the position of the word in the list, with positions numbered
   * from 0 to getWordCount() - 1.
   * @throws IndexOutOfBoundsException
   * if index is not in the range 0 to getWordCount() - 1.
   */
   public String removeWord(int index) {
       return words.remove(index);
   }

}

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