首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >完成Hangman游戏

完成Hangman游戏
EN

Code Review用户
提问于 2015-01-12 02:56:52
回答 1查看 524关注 0票数 3

这在很大程度上是可行的。我对编程非常陌生,所以请注意。

代码语言:javascript
复制
import java.util.*;
public class HangManP5 
{
private static Scanner k;
public static void main(String[] args) 
{
int attempts = 10;
int wordLength;
boolean solved;
k = new Scanner(System.in);

System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game! (Some answers have two words, usually the longer ones\n");
String word = getRandomWord();
int len = word.length(); 
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
    temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: "+len+" letters.");
while (attempts <= 10 && attempts > 0)
{
    System.out.println("\nAttempts left: " + attempts);
    System.out.print("Enter letter: ");
    String test = k.next();
    if(test.length() != 1) 
    {
        System.out.println("Please enter 1 character");
        continue;
    }
    char testChar = test.charAt(0);
    int foundPos = -2;
    int foundCount = 0;
    while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
    {
        temp[foundPos] = testChar;
        foundCount++;
        len--;
    }
    if(foundCount == 0)
    {
        System.out.println("Sorry, didn't find any matches for " + test);
    }
    else
    {
        System.out.println("Found " + foundCount + " matches for " + test);
    }
    for(int i = 0; i < temp.length; i++)
    {
        System.out.print(temp[i]);
    }
    System.out.println();
    if(len == 0)
    {
        break; //Solved!
    }
    attempts--;
}
if(len == 0)
{
    System.out.println("\n---------------------------");
    System.out.println("You did iiiiiiit!");
}
else
{
    System.out.println("\n---------------------------");
    System.out.println("Better luck next time, you didn't get the word!");
    System.out.println("It was \"" + word + "\"");
}
}
public static String getRandomWord() 
{
    switch(new Random().nextInt(5)) 
    {
        case 1:
            return "peace";
        case 2:
            return "nuts";
        case 3:
            return "dankmemes";
        case 4:
            return "fizz";
        case 5:
            return "awesome"; 
        default:
            throw new IllegalStateException("Something went wrong!");
    }
}
}
EN

回答 1

Code Review用户

回答已采纳

发布于 2015-01-12 06:49:42

对于初学者来说,这个程序还不错。您将getRandomWord()例程拆分为它自己的函数,这很好。但是,您应该做得更多,因为您的main()太长了,一眼就看不出来。

getRandomWord()函数有一个严重的错误,这是因为您误用了Random.nextInt(int n)Random.nextInt(int n)。该调用的可能输出为0、1、2、3、4。因此,它永远不会选择"awesome",并且可能抛出一个IllegalStateException。不过,我不建议为此使用switch语句,因为词汇表应该被视为数据,而不是代码。最好从字符串数组中选择一个随机元素。

您还有一个逻辑错误,它允许用户一次又一次地猜测同一个正确的字母,从而“获胜”。例如,如果这个单词是"fizz",并且用户猜测'z',那么您就会记录下还有两个空白。如果用户再次猜测“z”,则报告一次胜利。(你确实应该更好地处理重复的猜测,但至少你应该防止这种错误的胜利。)

main()函数顶部的变量声明块是不友好的--没有人喜欢阅读这些声明。相反,请在尽可能接近使用点的地方声明变量。实际上,在声明块中有两个未使用的变量wordLengthsolved,您自己已经忘记了这两个变量。

选择有意义的变量名称--不仅对你,而且对任何可能出现的程序员都是如此。而不是k (“键盘”的缩写),选择input (并立即初始化)。而不是temp (这不是临时的,所以它的意思必须是“模板”?),试试wordDisplay

建议实现

这主要是因为

  • main()代码重构为函数
  • 为清晰度重命名变量
  • 写一些循环更有说服力
代码语言:javascript
复制
import java.util.*;

public class HangMan {
    private static final String[] VOCABULARY = new String[] {
        "peace", "nuts", "dankmemes", "fizz", "awesome"
    };

    private static Scanner input = new Scanner(System.in);

    private static void intro() {
        System.out.println("Hey, what's your name?");
        String name = input.nextLine();
        System.out.println(name+ ", hey! This is a hangman game! (Some answers have two words, usually the longer ones)\n");
    }

    /**
     * Picks a word at random from the vocabulary.
     */
    public static String getRandomWord() {
        return VOCABULARY[new Random().nextInt(VOCABULARY.length)];
    }

    /**
     * Makes an array of placeholder characters the same length as the word.
     */
    private static char[] initWordDisplay(String word) {
        char[] wordDisplay = new char[word.length()];
        Arrays.fill(wordDisplay, '*');
        return wordDisplay;
    }

    /**
     * Prompts the user to enter a single-character guess (repeatedly
     * if necessary in case of errors).
     */
    private static char promptGuess() {
        do {
            System.out.print("Enter letter: ");
            String s = input.next();
            if (s.length() == 1)  {
                return s.charAt(0);
            }
            System.out.println("Please enter 1 character");
        } while (true);
    }

    /**
     * Fills <code>wordDisplay</code> with the guess, returning the
     * number of blanks correctly filled as a result.
     */
    private static int fillGuess(String word, char[] wordDisplay, char guess) {
        int foundCount = 0;
        for (int pos = 0; (pos = word.indexOf(guess, pos)) != -1; pos++) {
            if (wordDisplay[pos] != guess) {   // Prevent repeat guess
                wordDisplay[pos] = guess;
                foundCount++;
            }
        }
        return foundCount;
    }

    public static void main(String[] args) {
        intro();

        String word = getRandomWord();
        char[] wordDisplay = initWordDisplay(word);
        int blanksLeft = wordDisplay.length;

        System.out.print("\nWord to date: " + blanksLeft + " letters.");

        for (int attemptsLeft = 10; blanksLeft > 0 && attemptsLeft > 0; attemptsLeft--) {
            System.out.println("\nAttempts left: " + attemptsLeft);
            char guess = promptGuess();
            int foundCount = fillGuess(word, wordDisplay, guess);
            blanksLeft -= foundCount;

            if (foundCount == 0) {
                System.out.println("Sorry, didn't find any matches for " + guess);
            } else {
                System.out.println("Found " + foundCount + " matches for " + guess);
            }
            System.out.println(new String(wordDisplay));
        }

        if (blanksLeft == 0) {
            System.out.println("\n---------------------------");
            System.out.println("You did iiiiiiit!");
        } else {
            System.out.println("\n---------------------------");
            System.out.println("Better luck next time, you didn't get the word!");
            System.out.println("It was \"" + word + "\"");
        }
    }
}
票数 5
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/77284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档