Question

Write a Java program implementing a hangman game. This should be a multi file project, managed...

Write a Java program implementing a hangman game. This should be a multi file project, managed with the directory structure discussed in class, compiled with the ant tool (using a build.xml file), and packaged as a JAR file, ready for distribution. Instructions on how to generate these files are included in our lectures. You can practice with the files ready to compile attached to Lecture 24 (the TicTacToe class example).

Your project should include:

1. a text file for the dictionary of words used in the game. The game should randomly select a word from this text file, which should be stored in the resources directory

2. a class to handle the construction of the game board, as well as any operations needed to update the board at every turn of the game. For example, if the player does not guess the next letter from the secret word correctly, this helper class (similar to the Array helper class for the TicTacToe game) should update the board by drawing the next "limb" on the scaffolding, therefore it should have an Update() and a Print() method

3. a class Hangman to handle the game play. Similar to the TicTacToe game, this class should have a Turn() method, handling all the actions needed in the game during one turn (invitation for the user to enter the next letter, accepting user input, matching against the secret word, update of the word display to show all the letters guessed so far), a Play() method to handle all the turns in a loop controlled by the return value from EndGame(), an EndGame() method to check for the end-of-game condition etc.

This project will be graded not only based on its output (the game play observed at the command line), but especially based on elegance of programming and using the compile tools studied this semester. For example, hardcoding the state of the board repeatedly will be penalized.

The project should contain both games TicTacToe (code provided with Lecture 24) and Hangman, both of which should be part of the same  package games. This project, together with your homework assignments, will represent your portfolio for this class, and may be uploaded onto Watermark as per our department regulations.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.lang.Math;

class HangMan {

    private List<String> wordsList;
    private String availableLetters;
    private String secretWord;
    private char[] lettersGussed;

    public HangMan() {
        for(int i=0; i<25; i++)
            availableLetters = availableLetters + (char)(97+i);
       
    }

    public List<String> loadWords(String fileName) {
        wordsList = new ArrayList<String>();
        //your code goes here


    File f = new File(fileName);
    
    // Scanner sc= new Scanner(f);
    // while(sc.hasNextLine()){
    //     System.out.println(sc.next());
    // }
  char c;
  String word="";
try {
      FileInputStream fis = new FileInputStream(f);
      char current;
      while (fis.available() > 0) {
        c = (char) fis.read();
        if(((int)c>=65 && (int)c<=90))
        {
            System.out.println(word);
            wordsList.add(word);
            word="";
        }
        word+=c;
        System.out.println(c);
        
        //System.out.print(current);
      }
      wordsList.add(word);
      wordsList.remove(0);
      for(int i=0;i<wordsList.size();i++)
      {
        System.out.println(wordsList.get(i));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }




        return wordsList;
    }

    public boolean isWordGuessed(String secretWord, char[] lettersGussed) {
        //String lg = new String(lettersGussed);
        //your code goes here
        String result = "";
        for (int i = 0; i < secretWord.length(); i++) {
        if(!result.contains(String.valueOf(secretWord.charAt(i)))) {
            result += String.valueOf(secretWord.charAt(i));
        }
    }
    //System.out.println("result="+result);

        int flag=0,count=0;
        for(int i=0;i<result.length();i++)
        {   flag=1;
          for(int j=0;j<lettersGussed.length;j++ )
          {
            if(result.charAt(i)==lettersGussed[j])
            {
                count++;
          }}
          //if (flag==0)
            //break;
        }
        if (count==result.length())
        return true;
        else
        return false;

    }

    public String getGuessedWord(String secretWord, char[] lg) {
        //your code goes here
        //System.out.println(secretWord);
    String new_string="";
    int isSpace=0,flag=0,p=0;
    for (int i=0;i<secretWord.length();i++)
    {
        flag=0;
        p=0;
        for (int j=0;j<lg.length;j++)
        {   
            
            if (secretWord.charAt(i)==lg[j])
            {
                

                p=1;
                //System.out.println(new_string.length());
                if (new_string.length()>0)
                {
                 if (new_string.charAt(new_string.length()-1)=='_')
                    {//System.out.println(new_string.charAt(new_string.length()-1));
                
                        //System.out.println("deepak");
                        new_string+=" ";
                            }
                }
                new_string+=lg[j];
                break;
            }
            else
                flag=1;
        }
        if (flag==1 && p==0)
                new_string+=" _";
    }

    if (new_string.charAt(new_string.length()-1)==' '||new_string.charAt(0)==' ')
    {
        
        String s="";
        for(int i=0;i<new_string.length();i++)
        {
            if(!(new_string.charAt(i)==' '&&(i==0||i==(new_string.length()-1))))
                {s+=new_string.charAt(i);}
        }
        return s;
    }
else
    return new_string;
}

    public String getAvailableLetters(char[] lg) {
        String availableLetters = "";

            String alphabets="abcdefghijklmnopqrstuvwxyz";
        //    String avail_letters="";

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

            {   int flag=0;

            for(int j=0;j<lg.length;j++){
                if(alphabets.charAt(i)==lg[j])
                {
                    flag=1;
                    break;
                }
               }
               if (flag==0)
                 availableLetters+=alphabets.charAt(i);
               

            }


        //your code goes here
        return availableLetters;
    }
    public String chooseWord(List<String> wordsList )
    {
        
        String word=wordsList.get((int)Math.random()*wordsList.size());

        //your code goes here
        return word;
    }
    public void startHangMan(String secretWord)
    {
        //your code goes here

    int guess=8,flag;
    char[] lettersGuessed=new char[30];
    int size=0;
    String letter;
    Scanner sc=new Scanner(System.in);
    String alphabets,new_string;
    System.out.println("Length of the word to be guessed is "+secretWord.length());
    System.out.println("\n-----------------------------------------------");    
    while (guess>0)
    {
        System.out.println("\nYou have "+guess+" guesses left");
        alphabets=getAvailableLetters(lettersGuessed);
        System.out.println("\nAvailable letters : "+alphabets);
        System.out.println("\nGuess a letter : ");
        letter=sc.nextLine();
        
        if(Arrays.asList(lettersGuessed).contains(letter )) {

            
            System.out.println("You have aleady guessed this letter");
            new_string=getGuessedWord(secretWord,lettersGuessed);
            for (int i=0;i<new_string.length();i++)
                    System.out.print(new_string.charAt(i));
            }
        else
        {   
            flag=0;
            lettersGuessed[size++]=letter.charAt(0);
            for(int i=0;i<secretWord.length();i++)
            {
                if (letter.charAt(0)==secretWord.charAt(i))
                    {flag=1;
                        break;}
                
            }
            if (flag==1)//if letter in secretWord
            {   System.out.println("\nCorrect guess!");
                new_string=getGuessedWord(secretWord,lettersGuessed);
                for (int j=0;j<new_string.length();j++)
                    System.out.print(new_string.charAt(j));
            }
            else
                {
                System.out.println("Oops! Wrong guess.");
                guess-=1;
                new_string=getGuessedWord(secretWord,lettersGuessed);
                for (int j=0;j<new_string.length();j++)
                    System.out.print(new_string.charAt(j));
                }
        }
        if (isWordGuessed(secretWord,lettersGuessed))
        {
            System.out.println("\nCongratulations!You have won the game :) ");
            break;
        }
        System.out.println("----------------------------------------------");
        
    }
    if (guess<=0)
       { System.out.println("Sorry,you have lost the game :(");
        System.out.println("The word was :"+secretWord);
    }





    }
}

public class HangManGame {
    public static void main(String[] args) {
        HangMan hangMan = new HangMan();
        String secretWord = hangMan.chooseWord(hangMan.loadWords("words.txt")).toLowerCase();
        hangMan.startHangMan(secretWord);
        //you can call your function here 
        //foo.function_name(arg1, arg2, ...);
    }
}
Add a comment
Know the answer?
Add Answer to:
Write a Java program implementing a hangman game. This should be a multi file project, managed...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Hangman (game) In this project, you are required to implement a program that can play...

    C++ Hangman (game) In this project, you are required to implement a program that can play the hangman game with the user. The hangman game is described in https://en.wikipedia.org/wiki/Hangman_(game) . Your program should support the following functionality: - Randomly select a word from a dictionary -- this dictionary should be stored in an ASCII text file (the format is up to you). The program then provides the information about the number of letters in this word for the user to...

  • Consider a class that could be used to play a game of hangman. The class has...

    Consider a class that could be used to play a game of hangman. The class has the following attributes: The secret word. The disguised word, in which each unknown letter in the secret word is replaced with a question mark (?). For example, if the secret word is abracadabra and the letters a, b, and e have been guessed, the disguised word would be ab?a?a?ab?a. The number of guesses made. The number of incorrect guesses. It will have the following...

  • Create the game hangman using c code: Program description In the game of hangman, one player...

    Create the game hangman using c code: Program description In the game of hangman, one player picks a word, and the other player has to try to guess what the word is by selecting one letter at a time. If they select a correct letter, all occurrences of the letter are shown. If no letter shows up, they use up one of their turns. The player is allowed to use no more than 10 incorrect turns to guess what the...

  • For a C program hangman game: Create the function int play_game [play_game ( Game *g )]...

    For a C program hangman game: Create the function int play_game [play_game ( Game *g )] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) (Also the link to program files (hangman.h and library file) is below the existing code section. You can use that to check if the code works) What int play_game needs to do mostly involves calling other functions you've already...

  • Objective: To write a program to allow a game of Tic Tac Toe to be played,...

    Objective: To write a program to allow a game of Tic Tac Toe to be played, and to determine when the game is over Complete the TicTacToe program below. It will allow for a full game of Tic Tac Toe between two players, and it will tell you who won or if the game is over with no winner. Details: The TicTacToe board is stored in a 3x3 multidimensional list of characters containing spaces at the start of the game...

  • For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two p...

    For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two players race to reach 100 points. Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn,...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • Enhance and correct a Tic Tac Toe game. The game is intended to be played against...

    Enhance and correct a Tic Tac Toe game. The game is intended to be played against a computer. The object TicTacToeBoard is initialized to indicate if the computer is the player 1 or player 2. Your task is to allow turns between the player and computer and to determine if a winner exists. Keyboard input implies using the Scanner object. Review Section 7.7 in the textbook. Ideally, do 1 task at a time and test the results. The tasks are...

  • Write a program two classes that will complete this secret square game. First download the driver...

    Write a program two classes that will complete this secret square game. First download the driver and include it in your project. Next create a class Space with the following Instance variables hasBeenUncovered: a true or false value indicating whether or not the space had been checked isSecretSquare: a true or false value indicating if this space is the square Constructors Default: sets both instance variables to false Parameterized: Takes in two parameters that set the instance variables to those...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT