Hangman Java Code Reflection: I would like to have a reflection written upon the
ID: 3828550 • Letter: H
Question
Hangman Java Code Reflection: I would like to have a reflection written upon the java code hangman game program located below as if you are preparing to write and have written the code. Such as what the project's tasks are in order to complete the program, and the workflow you would use. How would your pseudocode look to plan the program out? How would your workflow look, and what lessons would you perhaps learn trying it the first time.Please no one or two sentence responses. I need a thorough reflection. Thank you for your time.
import java.util.*;
class Hangman
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int noOfGuesses =0,lettersCorrect=0;
String choiceToPlay, userGuess;
char menuChoice, letter;
char [] guessWord = {'h', 'e', 'l', 'l', 'o'};
char [] correctLetter = {'-', '-', '-', '-', '-'};
System.out.println("Hello and welcome to Hangman!");
//main game menu
do
{ System.out.println("Do you want to play? Press Y/N ");
choiceToPlay = keyboard.next();
menuChoice = choiceToPlay.charAt(0);
if(!(menuChoice == 'y'||menuChoice == 'Y'||menuChoice == 'n'||menuChoice =='N'))
{
System.out.println("You have entered an invalid option. Try again! ");
}//if invalid
}//do
while (!(menuChoice =='Y' ||menuChoice=='y'||menuChoice == 'n'|| menuChoice =='N'));
if(menuChoice == 'N'||menuChoice =='n')
{
System.out.println("You have chosen to leave the game.");
System.out.println("Goodbye!");
System.exit(0);
}//if
else
{
while(lettersCorrect <5)
{
//Getting users guess.
System.out.println(" The guess word has 5 letters.");
System.out.println("Enter a letter to guess: ");
userGuess = keyboard.next();
letter = userGuess.charAt(0);
//Incrementing letters each time.
noOfGuesses++;
if(letter == guessWord[0])
{
System.out.println("There is 1 H in the word");
System.out.println("You have guessed the first letter correctly.");
correctLetter[0] = letter;
System.out.println(correctLetter);
System.out.println("You have had " + noOfGuesses + " guesses, so far");
lettersCorrect++;
System.out.println("Letters correct so far: "+lettersCorrect);
}//if first letter
else if(letter==guessWord[1])
{
System.out.println("There is 1 E in the word");
System.out.println("You have guessed the second letter correctly.");
correctLetter[1] = letter;
System.out.println(correctLetter);
System.out.println("You have had " + noOfGuesses + " guesses, so far");
lettersCorrect++;
System.out.println("Letters correct so far: "+lettersCorrect);
}//if second letter
else if(letter ==guessWord[2]||letter==guessWord[3])
{
System.out.println("There are 2 L's in the word");
System.out.println("You have guessed the third and fourth letters correctly.");
correctLetter[2] = letter;
correctLetter[3]=letter;
System.out.println(correctLetter);
System.out.println("You have had " + noOfGuesses + " guesses, so far");
lettersCorrect+=2;
System.out.println("Letters correct so far: "+lettersCorrect);
}//if third and fourth letters
else if(letter ==guessWord[4])
{
lettersCorrect++;
System.out.println("There is 1 O in the word");
System.out.println("You have guessed the fifth letter correctly.");
correctLetter[4] = letter;
System.out.println(correctLetter);
System.out.println("You have had " + noOfGuesses + " guesses, so far");
System.out.println("Letters correct so far: "+lettersCorrect);
}//if fifth letter
else
{
System.out.println("The letter you guessed is not in the word. ");
System.out.println("Guesses taken so far: "+noOfGuesses);
System.out.println("Letters correct so far: "+lettersCorrect);
}//else incorrect letter
}//while loop
System.out.println(" You found the word!");
System.out.println("It was hello.");
System.out.println("Total guesses: "+noOfGuesses);
System.exit(0);
}//else
}//main
}//class
Explanation / Answer
Ans.
//Reflection with GUI
//First add words.txt which contains words in your project directory thenn add follwing classes to run the game
/*
* 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();
}
}
}
}
//
/*
* 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();
hangman.readFile("words.txt");
HangmanGameGUI.buildGUI();
setUpGame();
}
// 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?");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.