c++ - 我的井字游戏理论上是个大问题,但对我来说一切似乎都很好
问题描述
所以我进入了学习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
为假的代码。
如果玩家的移动不在对角线上,则检查不会运行。
修理:
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.
}
}
推荐阅读
- amp-html - 包含组件文件的顺序是否重要?
- android - 不知道在 MainActivity.java 中放置 CheckBox 代码的位置
- android - 我的 firebase 聊天应用程序未出现在要发送的消息应用程序列表中
- java - 底部导航栏不切换片段
- ionic-framework - 离子服务 livereload 代码更改中断
- sql - 按顺序、重复和全部返回 SQL 表。
- r - 如何将值向量传递给函数?
- reactjs - 反应导航 - 状态更新后导航到默认路线
- python - 替换 Python 3 中的文本,但它只读取一行
- python - python:检测冒名顶替用户名;匹配除特定字符替换之外的整个字符串