C 控制台Tictactoe:检查获胜条件
C++ console TicTacToe: Checking Win Conditions
游戏板被存储为2D char数组。玩家使用NUMPAD将光标移动到板上,并在光标的Enter键位置中进行选择。
每次移动后,使用以下方法对板进行胜利。
void checkwin()
{
//look along lines from current position
int x = cursorPosX;
int y = cursorPosY;
int c = playerTurn ? 1 : 2; //which mark to look for
for (int xAxis = 0; xAxis <= 2; xAxis++) //look along x axis
{
x = WrapValue(0, sizeof(squares[0]), x + 1);
if (CheckPos(x, y) != c) //if we don't find the same mark, must not be a horizontal line, otherwise, break out.
{
x = cursorPosX; //reset x
for (int yAxis = 0; yAxis <= 2; yAxis++) //look along y axis
{
y = WrapValue(0, sizeof(squares[0]), y + 1);
if (CheckPos(x, y) != c)
{
y = cursorPosY;
//look for diagonal
for (int i = 0; i <= 2; i++ )
{
x = WrapValue(0, sizeof(squares[0]), x + 1);
y = WrapValue(0, sizeof(squares[0]), y + 1);
if (CheckPos(x, y) != c)
{
//failed everything, return
winConditions = -1;
return;
}
}
break;
}
}
break;
}
}
//if we make it out of the loops, we have a winner.
winConditions = playerTurn ? 0 : 1;
}
我弄错了结果 - 在不合适的情况下返回抽奖或获胜。我几乎可以肯定的是x和y在某个时候会得到错误的值,然后开始检查错误的斑点。
Visual Studio进入Yaxis循环后停止更新X和Y的手表 - 我不确定为什么,但它阻止了我跟踪这些值。我是否打破了有关在某个地方进行范围的规则?这是我使用x和y作为变量名称的唯一位置。
以下相关的包装方法。我的目的是始终能够通过添加来检查其他两个空间,无论我在董事会上的位置
int WrapValue(int min, int max, int value)
{
auto range = max - min;
while (value >= max)
{
value -= range;
}
while (value < min)
{
value += range;
}
return value;
}
我很高兴受过训练的眼睛告诉我我在这里做错了什么。非常感谢您的时间。
嵌套是一个可怕的想法。我通过将代码重构为多个单独的循环来解决问题,这些循环做了1件事,而不是彼此陷入更深层次的地狱级别。
for (int xAxis = 0; xAxis <= 2; xAxis++) //look along x axis
{
x = WrapValue(0, sizeof(squares[0]), x + 1);
if (CheckPos(x, y) != c) //if we don't find the same mark, must not be a horizontal line, otherwise, break out.
{
x = cursorPosX; //reset x
break;
}
else if (xAxis == 2)
{
winConditions = playerTurn ? 0 : 1;
return;
}
}
for (int yAxis = 0; yAxis <= 2; yAxis++) //look along y axis
{
y = WrapValue(0, sizeof(squares[0]), y + 1);
if (CheckPos(x, y) != c)
{
y = cursorPosY;
break;
}
else if (yAxis == 2)
{
winConditions = playerTurn ? 0 : 1;
return;
}
}
...ect
这违反了干燥,但它确实按照应该的方式工作,我相信我以后可以简化。
虽然我不完全确定为什么以前的方法不起作用,但我确实意识到这只是糟糕的设计。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 我提出什么条件才能再加5%的折扣
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- Gomoku对角线获胜条件
- C 控制台Tictactoe:检查获胜条件
- 用于检查Gomoku获胜条件的C++正则表达式