这是C语言中的一款对战AI井字游戏。如果AI滚入了一个占满的位置,我该如何使它再次滚动直到到达一个空位?
char boardchar[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
void Turn()
{
/*Player's Turn*/
AIrandomizer();
AI = AI_roll();
if (AI == 1 && boardchar[0][0] == '1')
{
boardchar[0][0] = symbAI;
}
else if (AI == 2 && boardchar[0][1] == '2')
{
boardchar[0][1] = symbAI;
}
else if (AI == 3 && boardchar[0][2] == '3')
{
boardchar[0][2] = symbAI;
}
else if (AI == 4 && boardchar[1][0] == '4')
{
boardchar[1][0] = symbAI;
}
else if (AI == 5 && boardchar[1][1] == '5')
{
boardchar[1][1] = symbAI;
}
else if (AI == 6 && boardchar[1][2] == '6')
{
boardchar[1][2] = symbAI;
}
else if (AI == 7 && boardchar[2][0] == '7')
{
boardchar[2][0] = symbAI;
}
else if (AI == 8 && boardchar[2][1] == '8')
{
boardchar[2][1] = symbAI;
}
else if (AI == 9 && boardchar[2][2] == '9')
{
boardchar[2][2] = symbAI;
}
}
我已经尝试过使用switch(case)和多个ifs以及else ifs,但是我仍然无法找出解决此问题的方法。
答案 0 :(得分:2)
您可以使用while或do-while语句。
还要制作一个3x3二维数组,以跟踪斑点:0 =未填充,1 =人类,2 = AI(最好使用枚举)。
使用伪代码:
全局变量:
int spots[3][3]; // 3x3 array
代码:
Setup(); // Setup of board, sets 0's to spots.
while (!endOfGame())
{
Player(); // Handle player, assuming it plays first, sets a 1 in one spot
if (!endOfGame())
{
AI();
}
}
void AI()
{
do
{
square = AIChoice();
} while (spots[square] == 0);
// Now we know spots[square] == 0, thus unfilled
spots[square] = 2; // AI
}