Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
3.0 kB
3
Indexable
Never
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;




public class Hangman {
    
    private String secretWord;
    private String hint;
    private final List<String> GuessedWords=new ArrayList<String>();
    private String WrongGuess;
    
    final static String[] bodyParts={"head","body","left arm","right arm","left leg","right leg","Tail","Eyes","end"};
   
    static int index;
    
    static {
        index=0;
    }
    
    Hangman(String secretWord) {
        this.secretWord=secretWord;
        char[] fill = new char[secretWord.length()];
        Arrays.fill(fill, '?');
        hint= new String(fill);
        WrongGuess = "rope";
    }




    boolean gameOver() {
       if(!hint.contains("?"))
           return true;
       else return "end".equals(bodyParts[index]);
    }


    String guess(String next) {
       next=next.toLowerCase();
       
       if(secretWord.contains(next)){
           char[] temp=hint.toCharArray();     
           temp[secretWord.indexOf(next)]=next.charAt(0);
           hint= new String(temp);
           GuessedWords.add(next);
           
           char[] temp1=secretWord.toCharArray();
           temp1[secretWord.indexOf(next)]='$';
           secretWord=new String(temp1);
           return "good guess";
       }
       else{
           GuessedWords.add(next);
           WrongGuess +=" "+bodyParts[index];
           index++;
           return "bad guess";
       }
    }
    String getHint() {
       return hint;
    }
    
    @Override
    public String toString(){
        String retString=GuessedWords.toString()+'\n'+"Gallows = "+WrongGuess+"\n"+hint+"\n";
        return retString;
    }
    
}

import java.util.Scanner;

public class HangmanRunner {
    public static void main(String[] args){
        Scanner kb=new Scanner(System.in);
        String[] secretWords={"tiger","elephant","falco","lion","dove","sparrow","gopher"};
         
        while(true) {
        	Hangman game=new Hangman(secretWords[(int) (Math.random() * secretWords.length)]);
            System.out.println(game);
        	 while(!game.gameOver()){
                 System.out.print("guess a letter: ");
                 System.out.println(game.guess(kb.next()));
                 System.out.println(game);
             }
             
             if(game.getHint().indexOf('?')== -1)
                 System.out.println("you won");
             else
                 System.out.println("you lost");
             
             kb=new Scanner(System.in);
             
             System.out.print("\nDo you want to Play Again Press Y or Press Any Key to Quit: ");
             char choice=kb.nextLine().toLowerCase().charAt(0);
             
             if (choice!='y') {
            	 break;
             }
             System.out.println();
        }
       
            
    }
}