Tuesday, August 22, 2017

HangMan

Following Code is Hangman Like game without graphics inspired by Duta http:duta.in:


Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
static String check="AEIOU";
public static void main(String[] args) {
ArrayList<String> questions=new ArrayList<>();
questions.add("ABRUPTLY");
questions.add("BOOKWORM");
questions.add("GALAXY");
questions.add("PNEUMONIA");
questions.add("STRONGHOLD");
questions.add("WHIZZING");
questions.add("PUZZLING");
questions.add("WRISTWATCH");
questions.add("ZODIAC");
questions.add("THUMBSCREW");
questions.add("YACHTSMAN");
questions.add("MNEMONIC");
questions.add("TRANSPLANT");
questions.add("RHYTHM");
questions.add("MICROWAVE");
Collections.shuffle(questions);
String ques=questions.get(0);
   char[] given=new char[ques.length()];
   int count=0;
   for(int i=0;i<given.length;i++) {
    if(varcheck(ques.charAt(i))) {
    given[i]=ques.charAt(i);
    }else {
    given[i]='_';
    }
   }
   boolean win=false;
   Scanner in=new Scanner(System.in);
   StringBuffer buffer=new StringBuffer();
outer:
   while(count<7 && !win) {
    for(int i=0;i<given.length;i++) {
    System.out.print(given[i]+" ");
    }
    System.out.println();
    System.out.println("Guess a Letter");
    char c=in.nextLine().toUpperCase().charAt(0);
    int i=0;
    while(i<given.length) {
    if(given[i]==c) {
    System.out.println("Already Present in Word!!");
    System.out.println("Guessed Letters : "+buffer);
    System.out.println("Chances left : "+(7-count));
    System.out.println("------------------------------");
    continue outer;
    }i++;
    }
    if(buffer.toString().contains(c+"")) {
    System.out.println("Already Guessesed!!");
    System.out.println("Guessed Letters : "+buffer);
    System.out.println("Chances left : "+(7-count));
    System.out.println("------------------------------");
    continue outer;
    }
    if(ques.contains(c+"")) {
    int idx=ques.indexOf(c);
    while(idx>=0) {
    given[idx]=c;
    idx=ques.indexOf(c,idx+1);
    win=true;
    }
    System.out.println("Good Guess!!");
    }else {
    count++;
    System.out.println("Bad Guess!!");
    }
    buffer.append(c+",");
    System.out.println("Guessed Letters : "+buffer.toString().substring(0,buffer.length()-1));
    System.out.println("Chances left : "+(7-count));
    for(char x: given) {
    if(x=='_') {
    win=false;
    }
    }
    System.out.println("--------------------------------\n");
   }
    System.out.println("Word is : "+ques);
   if(win) {
    System.out.println("Congratulations,You win!!");
   }else {
    System.out.println("You Loose!!,Don't Worry Try Again");
   }
   in.close();
}
static boolean varcheck(char c) {
if(check.contains(c+"")) return true;
return false;
}

}

Output: