[英]Tic Tac Toe determine winner algorithm
I initially intended to post this on the Codereview SE but since I really didn't know if the following code could be considered complete, I thought it would be a better fit here. 我最初打算在Codereview SE上发布这个,但由于我真的不知道以下代码是否可以被认为是完整的,我认为这将更适合这里。 Feel free to close this if you feel it'd be better posted somewhere else. 如果您觉得在其他地方发布更好,请随意关闭它。
Considering a "valid" in terms of tic tac toe rules 3x3 array as input called game
, how does this algorithm look for finding out the winner? 考虑到tic tac toe规则3x3数组的“有效”作为输入称为game
,该算法如何寻找获胜者?
I'm a noob in C and programming in general and I'd like to know how good is the performance/complexity of this code, since it kind of differs from what I find on other posts in SO. 我是C语言和一般编程的菜鸟,我想知道这段代码的性能/复杂程度有多好,因为它与我在SO中的其他帖子中找到的有所不同。 Do the for loops make this unnecessarily complicated? for循环会使这不必要地变得复杂吗?
if (game[1][3] == game[2][2] && game[2][2] == game[3][1]) /*antidiagonal check */
{
w = game[1][3]; /* w is player X or O */
}
t1 = 0;
for (i=0; i<=2; ++i)
{
if (game[i][i] == game[i+1][i+1]) /* main diagonal check */
{
t1 += 1;
}
if (t1 == 2)
{
w = game[i][i];
}
}
for (i=0; i<=2; ++i)
{
t2 = 0;
for (j=0; j<=1; ++j)
{
if (game[i][j] == game[i][j+1]) /* row check */
{
t2 += 1;
if (t2 == 2)
{
w = game[i][j];
}
}
}
}
for (i=0; i<=1; ++i)
{
t3=0;
for (j=0; j<=2; ++j)
{
if (game[i][j] == game[i+1][j]) /* column check */
{
t3 += 1;
if (t3 == 2)
{
w = game[i][j];
}
}
}
}
if (t1<2 && t2<2 && t3<3)
{
printf("No winner\n");
}
else
{
printf("%c wins\n", w);
}
A tic-tac-toe board has 9 tiles. Tic-tac-toe板有9块瓷砖。
Each tile either has an X
in it or it doesn't. 每个瓷砖都有一个X
或它没有。 This means that you can use a 9-bit unsigned integer to represent if each tile does/doesn't have an X
; 这意味着您可以使用9位无符号整数来表示每个磁贴是否具有X
; then use this number in a (512 entry) lookup table to determine if X
won. 然后在(512条目)查找表中使用此数字来确定X
赢了。
In the same way; 以同样的方式; each tile either has an O
in it or it doesn't; 每个瓷砖要么有一个O
,要么没有; so you can encode that as a different 9-bit unsigned integer and use it in the same (512 entry) lookup table to determine of O
won. 因此,您可以将其编码为不同的9位无符号整数,并在相同的(512条目)查找表中使用它来确定O
won。
If the board is represented as a pair of 9-bit integers everywhere (avoiding the need to convert the state of the board), then the code becomes: 如果电路板在任何地方都表示为一对9位整数(避免转换电路板的状态),则代码变为:
if( table[XboardState] == WIN) {
printf("X wins\n");
} else if( table[OboardState] == WIN) {
printf("O wins\n");
} else {
printf("No winner\n");
}
Note: The lookup table only needs one bit per entry; 注意:查找表每个条目只需要一位; so by using bitfields (and some shifting/masking to select the right bit) it could be as small as 64 bytes. 因此,通过使用位域(以及一些移位/屏蔽来选择正确的位),它可以小到64字节。 Of course you could write a crude/temporary utility to generate the table for you, then "cut & paste" the table into your game's code. 当然,您可以编写一个原始/临时实用程序来为您生成表格,然后将表格“剪切并粘贴”到游戏代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.