我在Hangaman游戏中错过了什么?

时间:2018-07-07 09:18:13

标签: java

我是Java的新手,开始练习Hangman。 当然,有些人是在Github上制作man子手的,但我不明白为什么该人使子手更高级。这就是为什么我想自己练习。 我需要帮助的是一些建议。 我错过了什么,为什么从编译器中弄错了。

enter image description here

import java.util.Scanner;
public class HangMan {

private String answer;
public int hit, miss;
SketchHangMan sketchHangMan;

public HangMan() {
    this.answer = "banana";
    this.hit = 0;
    this.miss = 0;
    this.sketchHangMan = new SketchHangMan();
}//end contrctor Hangaman

public void displayResult(String show) {
    System.out.println(show);
}//end displayReult

public void convertTheAnswer() {
    char hide = '-';
    System.out.println("You have " + answer.length() + " letters to guess");
    System.out.print("Guess: ");

    for (char a : answer.toCharArray()) {
        System.out.print(hide);
    }//end for
    System.out.println();

}//end convertTheAnswer


public void checkTheAnswer(String userInput) {
    String display = "";
    for (int i = 0; i < answer.length(); i++) {
        char hide = '-';

        if (userInput.charAt(0) == answer.charAt(i)) {
            hide = userInput.charAt(0);

        }
        else {
            miss++;
        }//end if-else

        display += hide;
        sketchHangMan.sketchTheMan(miss);
    }//end for

    displayResult(display);

}//end checkTheAnswer
 }//end class

主Java:

public class StartGame {
    public static void main(String[] args) {

        HangMan hangMan = new HangMan();

    hangMan.convertTheAnswer();
    hangMan.checkTheAnswer("n");

}
}

素描the子手(只是文本)

public class SketchHangMan {
    int miss;

public void sketchTheMan(int userMissed) {
    this.miss = userMissed;
    switch (miss) {
        case 1:
            System.out.println("sketching the ground");
        case 2:
            System.out.println("Sketching the pole");
        case 3:
            System.out.println("sketching the rope");
        case 4:
            System.out.println("sketching the man, he is dead Game over");
            break;
    }//end switch case
}//end sketchTheMan
}//end class

1 个答案:

答案 0 :(得分:0)

第一个问题

sketchTheMan方法中,完成案例后,必须添加break才能继续进行下一个案例。

第二个问题

如果给玩家3个获得正确答案的机会,则您不想在sketchTheMan函数的循环的每次迭代中都调用checkTheAnswer函数。您可以在循环后调用该函数。您不会为每个遗漏的字母计入遗漏,只有在答案未包含用户猜到的单词时才计一次。您可以执行以下操作:

public void checkTheAnswer(String userInput) {
    String display = "";
    boolean scored = false;
    for (int i = 0; i < answer.length(); i++) {
        char hide = '-';

        if (userInput.charAt(0) == answer.charAt(i)) {
            hide = userInput.charAt(0);
            scored = true;
        }

        display += hide;

    }//end for
    //increment miss only if the answer doesn't contain the letter user guessed
    if(!scored) sketchHangMan.sketchTheMan(++miss); 
    displayResult(display);

}

用户也不必使用String作为猜测,因为用户只能猜测一个字母,因此更适合使用char