我想在已从终端打印到终端的二维数组的任何索引中输入一个字符

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

我对编程相当陌生,经过一系列教程后,我决定构建自己的井字游戏。 在制作棋盘并以表格形式打印之后,我现在要做的是能够从终端将字符(x和o)按顺序输入棋盘中玩家可能想要放置的位置,并在每次输入后打印。

这就是我所做的。该函数是 play() 函数。所有程序均采用 C++ 编写。我尝试的解决方案不允许我将字符输入到我想要的位置(索引):

class Board{
public:
    const static int rows = 5;
    const static int cols = 5;
    char grid[rows][cols]{};

    Board(){
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (j == 1 || j == 3) {
                    grid[i][j] = vertical;
                }

                if (i == 1 || i == 3) {
                    grid[i][j] = horizontal;
                }
            }
        }
    }

        void printBoard() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                cout << grid[i][j] << "\t";
            }
            cout << endl;
        }
    }

    void play() { 
       printBoard();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (Board().grid[i][j] != vertical && Board().grid[i][j] != horizontal) {
                    cin >> grid[i][j];
                }
            }
            printBoard();
        }
    }
};

在函数 play() 中,我尝试实现一个 for 循环,它允许我输入一个字符,并且在实现该字符后它将打印棋盘:

if (Board().grid[i][j] != vertical && Board().grid[i][j] != horizontal) { cin >> grid[i][j];

c++ tic-tac-toe
1个回答
0
投票

也许您可以存储光标的位置,并在 printBoard() 函数中“绘制”它。您可能需要另一个线程来更新光标的位置。 比如:

class Board{
public:
    const static int rows = 5;
    const static int cols = 5;
    char grid[rows][cols]{};

    Board(){
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (j == 1 || j == 3) {
                    grid[i][j] = vertical;
                }

                if (i == 1 || i == 3) {
                    grid[i][j] = horizontal;
                }
            }
        }
    }

    void printBoard() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                cout << grid[i][j] << "\t";
            }
            cout << endl;
        }
        // TODO draw the cursor here
    }

    void play() { 
       // TODO start a thread for Update()
       while(true) {
           printBoard();
       }
    }

    void Update() {
        while(true) {
            // TODO get a key from keyboard
            // TODO if the key is ↑↓←→: update cursorX and cursorY
            // TODO if the key is alpha, update the grid
        }
    }
private:
    int cursorX{0};
    int cursorY{0};
};
© www.soinside.com 2019 - 2024. All rights reserved.