【发布时间】:2017-09-24 13:52:25
【问题描述】:
我正在编写一个函数,用于检查“noughts and crosss”或“三连胜”游戏中是否有赢家。
游戏首先在命令提示符下绘制 3 x 3 方格。然后用户在方块之间移动光标,并按下回车键放置一个“X”。下一个选定的方块会在其中放置一个“O”,然后再次放置一个“X”,依此类推。在第 5 回合之后(第一个可能的回合可能有赢家),程序会在每回合之后检查是否有赢家,如果在 9 回合后没有找到赢家(当所有方格中都有东西时),则程序宣布平局。
但是,我编写的用于检查获胜者的函数在调用时总是返回 1,这意味着有获胜者(更具体地说,是 X,因为那是最后一步的人)。因此游戏在第 5 回合结束,无论方格包含什么。
这是我的代码:
int control(char p[3][3]) {
int i;
for (i = 0; i <= 3; i++) //Checks if any of the horizontals have 3 of the same markers in a row
if (p[i][1] == p[i][2] && p[i][2] == p[i][3])
return 1;
for (i = 0; i <= 3; i++) //Checks if any of the vertical columns have 3 of the same markers
if (p[1][i] == p[2][i] && p[2][i] == p[3][i])
return 1;
else if (p[1][1] == p[2][2] && p[2][2] == p[3][3]) //Checks if top left, middle and bottom right squares have the same marker
return 1;
else if (p[3][1] == p[2][2] && p[2][2] == p[1][3]) //Checks if the top right, middle and bottom left have the same marker
return 1;
else //If none of the above have the same 3 markers, the game keeps going
return 0;
}
【问题讨论】:
-
您是否尝试过逐步运行函数,通过调试器,甚至只用笔和纸?
-
在调试时,如果没有 X 或 O,请检查每个框中的内容。
-
您不能索引 3 x 3 矩阵中的第 4 行或第 4 列。
-
for (i = 0; i <= 3; i++)在数组大小仅为[3][3]时是错误的。 -
c是0基本数组,而不是1基本数组。该数组从[0][0]到[2][2],而不是从[1][1]到[3][3]。
标签: c function for-loop if-statement return-value