数组在Tic Tac Toe中表现不尽如人意?

时间:2013-11-20 21:09:07

标签: c++ arrays

我做了tictactoe! ......几乎。

代码:

int main()
{
    //initialize
    char board[3][3] =
    {   '-','-','-',
        '-','-','-',
        '-','-','-'};
    bool gameOver = false;
    std::string playerTurn = "player 1";
    char chX, chY; //choice x and y
    int x = 1;

    //game loop
    do
    {
        std::cout << "\n\n\n\n\n\n\n\n\n\n";
        std::cout << "Input X, then Y.\np1 = X, p2 = O.";
        std::cout << "\n\nTurn: " << playerTurn;
        std::cout << "\n\n\n\n\n\n\n\n\n\n";
        std::cout << "+---+---+---+" << std::endl;
        std::cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " | " << std::endl;
        std::cout << "+---+---+---+" << std::endl;
        std::cout << "| " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " | " << std::endl;
        std::cout << "+---+---+---+" << std::endl;
        std::cout << "| " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " | " << std::endl;
        std::cout << "+---+---+---+" << std::endl;

        //get input and change board's value
        std::cin >> chX;
        std::cin >> chY;
        if (playerTurn == "player 1")
            board[chX][chY] = 'X';
        else if (playerTurn == "player 2")
            board[chX][chY] = 'O';

        //change turns
        if (playerTurn == "player 1")
            playerTurn = "player 2";
        else if (playerTurn == "player 2")
            playerTurn = "player 1";

    } while (gameOver == false);
    return 0;
}

我的问题:

//get input and change board's value
std::cin >> chX;
std::cin >> chY;
if (playerTurn == "player 1")
    board[chX][chY] = 'X';
else if (playerTurn == "player 2")
    board[chX][chY] = 'O';

此作品用于将X和Y坐标更改为X / O,具体取决于轮到谁。但是,这根本不会改变板,也不会返回错误。 另外:board[0][0] = 't';会成功更改值,并在t点打印[0][0]

有什么我想念的吗?也许问题出在代码的其他地方? (如果问题太简单,我会提前道歉 - 也许我的咖啡太多了。)

3 个答案:

答案 0 :(得分:3)

这只是一个小错误 - 你将chX和chY定义为char,如果用户输入例如'1',它是'1'的ASCII码,而不是整数值1。

只需将您的声明更改为

即可
  int chX, chY;

它应该有用。

答案 1 :(得分:0)

将chars和chX中的chY和chX正确更改会导致数组的索引方式。

然后将此用作输入代码

std::cout << "Enter X corrdinate: ";
std::cin >> chX;
std::cout << "\n";
std::cin.clear();
std::cout << "Enter Y corrdinate: ";
std::cin >> chY;
std::cin.clear();
if (playerTurn == "player 1")
    board[chX][chY] = 'X';
else if (playerTurn == "player 2")
    board[chX][chY] = 'O';

Id还会创建第二个int类型的数组板,以便您可以检查玩家是否赢得了更轻松的

答案 2 :(得分:0)

char chX,chY; // valid values -127..128
std::cin >> chX; //gets ascii code of '0', '1' or whichever value you enter
std::cin >> chY;

问题是cin会返回你输入的字符的ascii代码; &#39; 0&#39 = 48;要获得整数值,只需减去&#39; 0&#39;:

  std::cin >> chX; 
    std::cin >> chY;
    chX -= '0';
    chy -= '0';