使用一些数组和循环的简化主脑游戏

问题描述 投票:0回答:2

这是我上课的一个项目。我仍然是一个初学者,因此本主题仅涵盖字符串,循环和数组。如果您不熟悉该游戏,则高级版本为this。但是,我的任务是使用更简单的版本。这是此版本的规则。

该程序首先要求第一个玩家(即代码制作者)输入要用于游戏的模式。图案长4个字母,每个字母代表一种颜色(R为红色,G为绿色)。为了简化游戏,只能使用两种颜色,红色和绿色。因此,例如,用户可以输入RRGR代表红色红色绿色红色,或者他们可以输入GGGG代表绿色绿色绿色绿色。为简化起见,您可以假设模式仅由R和/或G组成,代码制作者不会输入错误的字符或符号,但是,您必须检查代码制作者是否输入了正确的4个字符(长度为4个字符) ,而不是5和3)。如果没有,则需要提示直到他们这样做。编码人员可以输入大写或小写字母,您应该可以处理它。

程序还要求允许的最大猜测数。现在可以开始游戏了。代码破坏者现在可以猜测模式来赢得游戏。如果他们不能通过最大的猜测数这样做,他们就会输掉。为了帮助代码破解者,您的程序将在每次猜测后给出反馈。具体来说,对于确切位置正确的每种颜色,它将显示一个黑色的挂钩。对于不在正确位置但在图案中的每种颜色,它将显示白色钉。有关示例,请参见示例交互。详细要求和提示:

这里是其工作方式的示例:

Code maker, please enter a pattern of 4 colors (the possible colors are R=red and G=green):

GGGR

What is the maximum number of guesses allowed for this game?

4

Okay, now it's the code breaker's turn. You have 4 chances to guess the pattern. Enter a guess:

RRRR

The code maker sets out 1 black pegs and 0 white pegs. 

Enter a guess:

GGRG

The code maker sets out 2 black pegs and 2 white pegs

Enter a guess:

GGGR

You got the pattern! The code breaker wins!

我在哪里这么远

首先,我要计算黑钉。最好的方法是使用FOR循环将字符串输入转换为数组。有两个主要数组,一个是需要解决的原始模式,另一个是用户进行的所有尝试的try数组。然后,我们使用FOR循环比较数组内容,并在每次匹配时添加一个黑色的挂钩。

这是我关注的代码(计算黑针)。到目前为止,我的问题是我无法获得与每个数组内容匹配的引脚。基本上,即使有的时候它总是3针或2,但总会产生4针。如果需要,整个未完成的代码都在这部分之下。

String pattern = keys.nextLine().toUpperCase(); // this is used to enter the original pattern
String attempt = keys.nextLine().toUpperCase(); // this is to enter an attempt

String pattern_array [] = new String [5];
String attempt_array [] = new String [5];

int i;          
int black_pegs = 0;
for (i=0; i<pattern.length(); i++) {
    pattern_array[i] = pattern.substring(i,(i+1)); 
}
for ( i=0; i<attempt.length();i++) {
    attempt_array[i] = attempt.substring(i,i+1);
}
for (int x=0; x<4; x++) {
    if (pattern_array[i]==attempt_array[i]) {
        black_pegs++;
    }
}

这是我到目前为止的代码(如果愿意,可以看一下并指出其他内容)

import java.util.Scanner;
public class CopyOfAssignment5 {
    public static void main(String[] args) {
        Scanner keys = new Scanner(System.in);
        System.out.println("Codemaker, please enter a pattern of 4 colors (the possible colors are R=red and G=green");
        String pattern = keys.nextLine().toUpperCase();
        System.out.println("What is the maximum number of guesses for this game?");
        int number_of_guesses = keys.nextInt();
        int turns = number_of_guesses + 1;
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("Okay, now its the codebreaker's turn. You have " + number_of_guesses
                + " chances to guess the pattern");
        System.out.println("Enter a Guess:");

        int white_pegs = 0, black_pegs = 0;
        String pattern_array[] = new String[5];
        String attempt_array[] = new String[5];
        String attempt = null;

        while (turns > 0) { // while turns are not zero
            attempt = keys.nextLine().toUpperCase(); // then keep displaying the scanner input for an attempt.
            turns--;
        }
        if (attempt.equals(pattern)) { // if you get the correct patter, then you win. Loops stops.
            System.out.println("You got the pattern! The codebreaker wins!");
        }
        if (turns == 0 && !(attempt.equals(pattern))) {
            System.out
                    .println("The codemaker sets out " + black_pegs + " black pegs and " + white_pegs + " white pegs.");
            System.out.println("Sorry, that was your last chance. You lost.");
        } else if (turns < turns) {
            System.out
                    .println("The codemaker sets out " + black_pegs + " black pegs and " + white_pegs + " white pegs.");
            System.out.println("Enter a Guess:");
        }

        int i;
        for (i = 0; i < pattern.length(); i++) {
            pattern_array[i] = pattern.substring(i, (i + 1));
        }
        for (i = 0; i < attempt.length(); i++) {
            attempt_array[i] = attempt.substring(i, i + 1);
        }
        for (int x = 0; x < 4; x++) {
            if (pattern_array[i] == attempt_array[i]) {
                black_pegs++;
            }
        }
    }
}
java arrays string loops java.util.scanner
2个回答
1
投票

程序中有很多错误。

只要转弯还没有结束,就需要保持while循环运行。我看到}的右括号while loop放错了位置。

找到模式时需要从循环中中断。

turns < turnsturns == 0在循环内没有意义。因为在这种情况下,它无法进入循环。

您不需要创建新的String数组。您可以使用String的chatAt()方法。(尽管这不是逻辑错误)

读取输入内容时出现错误。使用Scanner.nextInt()后,应按照说明使用scanner.nextLine() here

使int white_pegs = 0, black_pegs = 0;局部变量相对于循环。以下是完整的工作代码。

public class CopyOfAssignment5 {

public static void main(String[] args) {
    Scanner keys = new Scanner(System.in);

    System.out.println("Codemaker, please enter a pattern of 4 colors (the possible colors are R=red and G=green");
    String pattern = keys.nextLine().toUpperCase();
    System.out.println("What is the maximum number of guesses for this game?");

    int number_of_guesses = keys.nextInt();
    keys.nextLine();
    int turns = number_of_guesses + 1;
    System.out.println();
    System.out.println();
    System.out.println();
    System.out.println();
    System.out.println("Okay, now its the codebreaker's turn. You have " + number_of_guesses
            + " chances to guess the pattern");
    System.out.println("Enter a Guess:");

    String attempt = null;

    while (turns > 0) { // while turns are not zero
        attempt = keys.nextLine();
        attempt = attempt.toUpperCase(); // then keep displaying the scanner input for an attempt.
        turns--;

        if (attempt.equals(pattern)) { // if you get the correct patter, then you win. Loops stops.
            System.out.println("You got the pattern! The codebreaker wins!");
            break;// Exit from while
        }

        // count black and white pegs to set.

        int rCountInPattern = 0;
        int gCountInPattern = 0;

        int rCountInAttempt = 0;
        int gCountInAttempt = 0;
        int white_pegs = 0, black_pegs = 0;

        for (int i = 0; i < 4; i++) {
            if (pattern.charAt(i) == attempt.charAt(i)) {
                black_pegs++;
            } else {
                if (pattern.charAt(i) == 'R') {
                    rCountInPattern++;
                } else {
                    gCountInPattern++;
                }

                if (attempt.charAt(i) == 'R') {
                    rCountInAttempt++;
                } else {
                    gCountInAttempt++;
                }
            }
        }

        white_pegs = Math.min(rCountInPattern, rCountInAttempt);
        white_pegs = white_pegs + (Math.min(gCountInPattern, gCountInAttempt));

        System.out
                .println("The codemaker sets out " + black_pegs + " black pegs and " + white_pegs + " white pegs.");
        System.out.println("Enter a Guess:");

    }

    if (turns <= 0) {
        System.out.println("Sorry, that was your last chance. You lost.");
    }

}

}

尽管有很多事情需要改进,但我发布的答案与您的解决方案并没有太大不同,以便您可以更好地理解它。

编辑:我的回答只是一个最小的工作解决方案,它可以为您提供输出。@Abra提供了更模块化,更易读的代码。


1
投票

这是我的实现。因为您已经接受了答案,所以我不会解释代码。也许您仍然希望将自己的代码与我的代码进行比较。也许其他人也会着手解决这个问题,并从下面的代码中受益匪浅。

public class MstrMind {
    private static final char  BLACK = 'B';
    private static final char  WHITE = 'W';
    private static final int  CODE_LENGTH = 4;

    private static String getCode(Scanner stdin) {
        System.out.println("Code maker, please enter a pattern of " + CODE_LENGTH + " colors (the possible colors are R=red and G=green):");
        String code = stdin.nextLine();
        while (!isCodeValid(code)) {
            System.out.println("Entered code does not contain " + CODE_LENGTH + " colors.");
            System.out.println("Code maker, please enter a pattern of " + CODE_LENGTH + " colors (the possible colors are R=red and G=green):");
            code = stdin.nextLine();
        }
        return code.toUpperCase();
    }

    private static int getGuesses(Scanner stdin) {
        System.out.print("What is the maximum number of guesses allowed for this game? ");
        int guesses = stdin.nextInt();
        stdin.nextLine();
        return guesses;
    }

    private static boolean guess(Scanner stdin, String code) {
        System.out.print("Enter a guess: ");
        String guess = stdin.nextLine();
        char[] flags = new char[CODE_LENGTH];
        int blackCount = 0;
        int whiteCount = 0;
        for (int i = 0; i < CODE_LENGTH; i++) {
            if (guess.charAt(i) == code.charAt(i)) {
                flags[i] = BLACK;
                blackCount++;
            }
            else {
                for (int j = 0; j < CODE_LENGTH; j++) {
                    if (guess.charAt(j) == code.charAt(i)  &&  flags[j] == 0  &&  i != j) {
                        flags[j] = WHITE;
                        whiteCount++;
                    }
                }
            }
        }
        boolean guessed = blackCount == CODE_LENGTH;
        if (!guessed) {
            System.out.printf("The code maker sets out %d black pegs and %d white pegs.%n",
                              blackCount,
                              whiteCount);
        }
        else {
            System.out.println("You got the pattern! The code breaker wins!");
        }
        return guessed;
    }

    private static boolean isCodeValid(String code) {
        return code != null && code.length() == CODE_LENGTH;
    }

    private static void playGame(Scanner stdin, String code, int guesses) {
        int guess = guesses;
        boolean guessed = false;
        while (guess > 0  &&  !guessed) {
            guessed = guess(stdin, code);
            guess--;
        }
        if (!guessed) {
            System.out.println("Code breaker failed to break the code. Code maker wins.");
        }
    }

    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        String code = getCode(stdin);
        int guesses = getGuesses(stdin);
        System.out.printf("Okay, now it's the code breaker's turn. You have %d chances to guess " +
                                                                                  "the pattern.%n",
                          guesses);
        playGame(stdin, code, guesses);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.