【问题标题】:Simplified mastermind game that uses a few arrays and loops使用一些数组和循环的简化策划游戏
【发布时间】:2020-03-22 03:22:53
【问题描述】:

这是我的一个课程项目。我还是个初学者,所以这个话题应该只涵盖字符串、循环和数组。如果对游戏不熟悉,进阶版是this。但是,我的任务是更简单的版本。这是此版本的规则。

程序首先要求第一个玩家(代码制作者)输入要用于游戏的模式。图案长 4 个字母,每个字母代表一种颜色(R 为红色,G 为绿色)。
为了简化游戏,只有两种颜色可以使用,红色和绿色。例如,用户可以输入 RRGR 来表示 Red Red Green Red,或者他们可以输入 GGGG 来表示 Green Green Green Green。为简化起见,您可以假设该模式仅由 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 循环将字符串输入转换为数组。有两个主要数组,需要解决的原始模式,以及用户完成的所有尝试的尝试数组。然后我们使用 FOR 循环来比较数组内容,并在每次匹配时添加一个黑色钉子。

这是我关注的代码(计算黑色引脚)。到目前为止,我的问题是我无法让引脚与每个数组内容相匹配。基本上,它总是导致 4 个引脚,即使有时它应该是 3 个或 2 个引脚。如果需要,整个未完成的代码都在这部分下面。

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


    【解决方案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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      你的程序有很多错误。

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

      当你找到模式时,你需要打破循环。

      turns &lt; turnsturns == 0 在循环内没有意义。因为,在那种情况下,它是不可能进入循环的。

      您不需要创建新的字符串数组。你可以使用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 提供了更模块化、更易读的代码。

      【讨论】:

        猜你喜欢
        • 2013-11-30
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-21
        相关资源
        最近更新 更多