所以我进入了学习c ++的下一步,那是一个矩阵。我试图做一个简单的井字游戏,但我的游戏无法正确检查游戏是否结束。如果您在第一轮中将height = 2和width = 2表示您会赢...我不知道我可以把它搞砸了,在我看来,这一切都还不错...
int map[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
map[i][j] = 0;
}
}
bool finished = false;
int player = 1;
while (!finished) {
//attack
cout << "player " << player << " it is your turn"<< endl;
cout << "The map looks like this:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
bool correctMove;
int height, width;
do
{
correctMove = true;
cout << "Where do you want to attack?" << endl;
cout << "height = "; cin >> height;
cout << "width = "; cin >> width;
if (map[height][width] != 0 || width > 2 || height > 2) {
correctMove = false;
}
} while (!correctMove);
map[height][width] = player;
//check finish game
bool foundSequenceLine = true;
for (int i = 0; i < 3; i++) {
if (map[height][i] != player) {
foundSequenceLine = false;
}
}
bool foundSequenceColumn = true;
for (int i = 0; i < 3; i++) {
if (map[i][width] != player) {
foundSequenceColumn = false;
}
}
bool foundSequenceDiag1 = true;
if (height == width) {
for (int i = 0; i < 3; i++) {
if (map[i][i] != player) {
foundSequenceDiag1 = false;
}
}
}
bool foundSequenceDiag2 = true;
if (height + width == 2) {
for (int i = 0; i < 3; i++) {
if (map[2-i][i] != player) {
foundSequenceDiag2 = false;
}
}
}
if (foundSequenceColumn || foundSequenceLine || foundSequenceDiag1 || foundSequenceDiag2) {
finished = true;
cout << "Congrats player " << player << " you won!!!";
}
//change turn
if (player == 1) {
player++;
}
else {
player--;
}
}
}
您的代码假设玩家已经赢了,除非您能完全证明他们没有赢。问题是您然后将证明该举动不是获胜举动的两个测试短路。
看看这段代码在做什么:
bool foundSequenceDiag1 = true;
if (height == width) {
for (int i = 0; i < 3; i++) {
if (map[i][i] != player) {
foundSequenceDiag1 = false;
}
}
}
首先,您说“玩家赢了” foundSequenceDiag1=true;
。然后,您说:“是在对角线上移动吗?”,然后您才运行可以将foundSequenceDiag1
设置为false的代码。
如果玩家进行的移动不在对角线上,则支票将不会运行。
修复:
bool foundSequenceDiag1 = (height==width); // true if the player played on diagonal
if (foundSequenceDiag1) { // loop code now only executes if player played on diagonal
for (int i = 0; i < 3; i++) {
if (map[i][i] != player) {
foundSequenceDiag1 = false;
}
}
}
如果我在写支票,一旦找到答案,我会使用break
关键字来停止查找。
for (int i = 0; i < 3; i++) {
if (map[i][i] != player) {
foundSequenceDiag1 = false;
break; // can't be true now, so stop checking.
}
}