检查数组中的元素是否已被占用

时间:2014-04-03 21:52:05

标签: c++ arrays

我正在制作一个双人tic tac toe游戏,玩家在1-9格中输入一个数字。玩家X使用变量Xp进入所需位置。而玩家O也是如此。但是,我无法制作一个if语句来检查玩家是否进入已经被占用的网格点。

#include <iostream>

using namespace std;

void showBoard(char board[], int turn, int Xp, int Op);
void winning(char board[]);


int main()
{

 int Xp=0, Op=0, turn=0;
 char board[9] = {'1','2','3','4','5','6','7','8','9'};

showBoard(board, turn, Xp, Op);

return 0;
}

void showBoard(char board[], int turn, int Xp, int Op)
{
cout << "Please enter a number on the board that is the spot you wish to use" << endl;

cout << "Board:\n";

cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;

do
{
for (turn=1; turn<10; turn++)
    if (!(turn % 2) == 0)
    {
        cout << "\nPlayer X's turn." << endl;
        cin >> Xp;
        if(Xp=Op) //HERE IS THE CHECKER
        {
            cout << "Spot is taken! Enter new spot: ";
            cin >> Xp;
            board[Xp-1] = 'X';
        }
        else
        {
        board[Xp-1] = 'X';
        }       //WHERE IT ENDS
cout << "Current Board:\n";

cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;

winning(board);
    }
    else
    {
        cout << "\nPlayer O's turn." << endl;
        cin >> Op;
        board[Op-1] = 'O';

cout << "Current Board:\n";

cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;

winning(board);
    }

}while(turn<10);

cout << "No one won.\n";

return;
}

2 个答案:

答案 0 :(得分:0)

将所有内容初始化为虚拟值

#define DUMMY_CHAR '.'

为Xp和Op

选择了一个字符
#define XP_CHAR 'X'
#define OP_CHAR 'O'

在你的支票中,做

if (board[Xp] != DUMMY_CHAR) // Your checker 

答案 1 :(得分:0)

首先,您要分配,而不是检查相等。

其次,Xp == Op仍然没有任何意义。用o点检查x点?更好的方法是检查广场是否为X还是O

if(board[Xp - 1] != 'X' || board[Xp - 1] != 'O')