Упрощенная игра вдохновителя, которая использует несколько массивов и циклов - PullRequest
0 голосов
/ 22 марта 2020

Это проект, который у меня есть для класса. Я все еще новичок, так что этот topi c должен охватывать только строки, циклы и массивы. Если вы не знакомы с игрой, расширенная версия это . Однако передо мной стоит более простая версия. Вот правила этой версии.

Программа начинается с того, что первый игрок, создатель кода, просит ввести шаблон, который будет использоваться для игры. Длина шаблона составляет 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 l oop для сравнения содержимого массива и добавляем черный колышек каждый раз, когда они совпадают при попытке.

Это код, на котором я сосредоточен (вычисление черных выводов). Моя проблема до сих пор состоит в том, что я не могу заставить выводы соответствовать каждому содержимому массива. По сути, это всегда приводит к 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++;
    }
}

Это мой код того, что у меня есть до сих пор (не стесняйтесь взглянуть и указать на другие вещи, если вы будете sh)

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++;
            }
        }
    }
}

Ответы [ 2 ]

2 голосов
/ 22 марта 2020

Вот моя реализация. Я не буду объяснять код, так как вы уже приняли ответ. Возможно, вы захотите сравнить свой код с моим. И, возможно, другие люди займутся этим вопросом и получат некоторую пользу от приведенного ниже кода.

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);
    }
}
1 голос
/ 22 марта 2020

В вашей программе много ошибок.

Вам нужно держать, пока l oop работает, пока ходы не закончились. Я вижу закрывающую скобку } для while loop не на своем месте.

Вы должны оторваться от l oop, когда найдете шаблон.

turns < turns и turns == 0 внутри l oop не имеет смысла. потому что в этом случае он никак не может войти в l oop.

Вам не нужно создавать новый массив String. Вы можете использовать метод String chatAt() (хотя это не логичная ошибка)

Ошибка чтения ввода. После использования Scanner.nextInt() вы должны использовать scanner.nextLine() как указано здесь

Сделать int white_pegs = 0, black_pegs = 0; локальными переменными относительно l oop. Ниже приводится полный рабочий код.

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 дал более модульный, более читаемый код.

...