Java 猜英文字

有一種遊戲叫做 Hangman

就是猜英文字 ie 答案是 program

(Guess) Enter a letter in word ******* > p

(Guess) Enter a letter in word p****** > r

(Guess) Enter a letter in word pr**r** > p

p is already in the word ----------->p已經猜過了

(Guess) Enter a letter in word pr**r** > o

(Guess) Enter a letter in word pro*r** > g

(Guess) Enter a letter in word progr** > n

n is not in the word ------------>猜錯了

(Guess) Enter a letter in word progr** > m

(Guess) Enter a letter in word progr*m > a

The word is program. You missed 1 time --------->計算錯幾次

Do you want to guess another word? Enter y or n> 是否要繼續玩 ??

想了一個下午

架構還是有點亂

有人可以給我提示嗎 ??

string [] words ={"dog", "cat", "rat"}; // 可以隨機選謎底

num = radom between 0 and 2;

boolean game_not_over =false;

while game_not_over { //方法也是還思索不出來

check if in puzzle // 謎底有沒有中

if yes uncover the letter;

if all letters found game over

if no give message letter is not in puzzle

}

1 Answer

Rating
  • 7 years ago
    Favorite Answer

    import java.util.Scanner;

    public class Hangman {

    public static void main(String[] args) {

    // 建立字典

    String words[] = {"banana","apple","orange","dog","cat"};

    String x;

    Scanner input = new Scanner(System.in);

    int alpha[] = new int[26];

    int i, num, tmp, len, correct, err;

    boolean play;

    do{

    play=true; err=0;

    num = (int)(Math.random()*words.length); // 決定字串

    len = words[num].length(); // 計算答案字串長度

    for (i=0;i<26;i++) alpha[i]=0; // 所有字母歸零

    for (i=0;i<len; i++){

    tmp = words[num].charAt(i)-'a';

    alpha[tmp]=1; // 用到的字母為1

    }

    do{

    correct=0;

    System.out.print("(Guess) Enter a letter in word ");

    for (i=0;i<len;i++) {

    tmp = words[num].charAt(i)-'a'; // 計算字母與a的距離

    if (alpha[tmp]==1) System.out.print("*");

    else { System.out.print(words[num].charAt(i)); correct++;}

    // 如果紀錄是1, 表示還沒猜過, 2 表示已經猜過, 0表示沒用到

    }

    if (correct!=len) // 答對的字母數還不夠

    {

    System.out.print(" >");

    x = input.nextLine();

    x = x.toLowerCase();

    tmp = x.charAt(0)-'a';

    if (alpha[tmp]==0) {System.out.println(x.charAt(0)+ " is not in the word"); err++;} // 錯誤值加1

    else if (alpha[tmp]==2) System.out.println(x.charAt(0)+ " is already in the word");

    else alpha[tmp]=2;

    }

    }while(correct!=len);

    // 答對之後的輸出和問題Y/N

    System.out.println();

    System.out.println("You missed "+err+" times");

    System.out.print("Do yo want to guess another word? Y/N");

    x = input.nextLine();

    x = x.toLowerCase();

    if (x.charAt(0)=='y') play=true; else play=false;

    }while(play==true);

    }

    }

Still have questions? Get your answers by asking now.