前言
hangman游戏界面
二、使用步骤
package game;
import java.util.Scanner;
import java.util.Random;
public class Hangman {
// String word = "australia";
String word[] = {"japan","qatar","syria","mongolia","bahrain","india"};
public void showMenu() {
System.out.println("-----Menu-----");
System.out.println("1.Play");
System.out.println("2.Instructions");
System.out.println("3.Exit");
System.out.print("\nChoose the option:");
int option;
Scanner sc = new Scanner(System.in);
System.out.println("\n输入数字");
option = sc.nextInt();
switch (option) {
case 1:
playGame();
break;
case 2:
instructGame();
break;
case 3:
exitGame();
break;
default:
System.out.println("Incorrect menu option");
showMenu();
break;
}
}
public void playGame() {
System.out.println("PlayGame method is invoked");
/*
* int flag = 0;
String input ,guess;
Scanner sc = new Scanner(System.in);
do {
System.out.println("\nEnter your guess");
input = sc.nextLine();
for(int i = 0;i<word.length();i++) {
if(word.charAt(i) == input.charAt(0)) {
flag = 1;
}
}
if(flag == 1) {
System.out.println("this letter is present in the word");
}else {
System.out.println("this letter is not present in the word " );
}
System.out.println("Do want to guess again(y/n)");
guess = sc.nextLine();
flag = 0;
}while(guess.equals("y")||guess.equals("Y"));
*/
int len,count = 0,rnd,flag = 0;
String choice,temp;
Random rd = new Random();
Scanner input = new Scanner(System.in);
rnd = rd.nextInt(6);
len = word[rnd].length();
char[] newString = new char[len];
StringBuffer wrgString = new StringBuffer();
for(int j = 0;j <len;j++) {
System.out.println("_ ");
}
System.out.println();
do {
flag = 0;
System.out.println("\n\nEnter your guess");
String ch = input.nextLine().toLowerCase();
count++;
for(int i = 0;i<len;i++) {
if(word[rnd].charAt(i) == ch.charAt(0)) {
newString[i] = word[rnd].charAt(i);
flag = 1;
}
}
if(flag == 0) {
flag = 1;
wrgString.append(ch+",");
System.out.println("\nMisses:" + wrgString);
}
System.out.println(newString);
temp = new String(newString);
if(word[rnd].equals(temp)) {
System.out.println("----Congrats :)You won----");
System.out.println("Do you want to play again(y/n)");
choice = input.nextLine();
if(choice.equalsIgnoreCase("y")) {
playGame();
}else {
showMenu();
}
}
}while(flag != 0);
}
public void instructGame() {
System.out.println("instructGame method is invoked");
}
public void exitGame() {
System.out.println("exitGame method is invoked");
System.exit(0);
}
public static void main(String[] args) {
Hangman hg = new Hangman();
hg.showMenu();
}
}
总结
学习。