Нужна помощь с циклом в игре Tic Tac Toe - PullRequest
0 голосов
/ 29 мая 2019

Моя программа выходит без итерации. Он автоматически переходит к «ВЫ выиграли». Без функции чемпиона программа работает нормально. Это, вероятно, какая-то очевидная ошибка, которую я пропустил. Если кто-нибудь может, пожалуйста, я был бы очень признателен.

#include <iostream>
#include <string>

#define GRID_SIZE 3

class TicTacToe {
private:
    char map[GRID_SIZE][GRID_SIZE];

public:

    void champion() {
        const char *possiblities[8]{
                "123"
                "456"
                "789"
                "147"
                "159"
                "258"
                "369"
                "753"
        };

        for (int i = 0; i < 8; i++) {
            bool winner = true;
            char previous_pos = '0';
            const char *possible_moves = possiblities[i];

            for (int index = 0; index < GRID_SIZE; index++) {
                char character = possible_moves[i];
                int entered_num = character - '0';
                int grid_space = entered_num - 1;
                int row = index / GRID_SIZE;
                int col = index % GRID_SIZE;

                char grid_coordinate = map[row][col];

                if (previous_pos == '0') {
                    previous_pos = grid_coordinate;
                } else if
                        (previous_pos == grid_coordinate) {
                    continue;
                } else {
                    winner = false;
                    break;
                }
            }
            if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

        }


    }

    void playgame() {
        std::string input;

        while (true) {
            std::cout << "Go player one" << std::endl;
            getline(std::cin, input);
            if (input != " ") {
                char entered = input.c_str()[0];

                if (entered >= '1' && entered <= '9') {
                    int entered_num = entered - '0';
                    int index = entered_num - 1;
                    int row = index / 3;
                    int col = index % 3;
                    char grid_position = map[row][col];

                    if (grid_position == 'X' || grid_position == 'O') {
                        std::cout << "Space taken. Try again" << std::endl;
                    } else {
                        map[row][col] = (char) 'X';
                        break;
                    }

                } else {
                    std::cout << "Only numbers 1 - 9" << std::endl;
                }
            } else {
                std::cout << "Have to enter something, try again" << std::endl;
            }


        }
    }

    void generateGrid() {
        int number = 1;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                map[x][y] = std::to_string(number).c_str()[0];
                number += 1;
            }
        }
    }

    void tictacToeMap() {


        std::cout << std::endl;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                std::printf(" %c ", map[x][y]);
            }
            std::cout << std::endl;
        }

    }


    TicTacToe() {
        generateGrid();
        while (true) {
            tictacToeMap();
            playgame();
            champion();


        }
    }
};


int main() {

    TicTacToe tic;
    tic.playgame();


    return 0;


}

Ответы [ 2 ]

0 голосов
/ 29 мая 2019

Сначала сделайте то, что сказал Макс Мейер, заменив if(winner = true) на if(winner == true). Но программа все еще не работает. Проблема в том, что в вашем строковом массиве вы не разделяете каждую строку запятой, поэтому, когда мой отладчик нажимает const char *possible_moves, он просто назначает весь массив, соединенный вместе. Поэтому просто разделяйте каждую строку в массиве возможностей запятой, например:

const char *possiblities[8]{
                "123",
                "456",
                "789",
                "147",
                "159",
                "258",
                "369",
                "753"
        };
0 голосов
/ 29 мая 2019

Проблема здесь:

if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

Вы, вероятно, имели в виду:

if (winner == true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...