gpt4 book ai didi

C++ - 连续检查 3

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:29 24 4
gpt4 key购买 nike

我有这个 3 x 3 的字符数组,它应该代表一个井字棋盘,之前,我会使用一堆“if”语句来查看是否有 3 个连续。

... 如果((板[0][0] ==板[0][1])&&(板[0][1] ==板[0][2])){ ... } ...

我意识到这是大量的输入,而且很容易出错,那么有更好的方法吗?

最佳答案

您可以将其更改为仅从最后一步移动的位置开始检查。

//lr = lastMoveRow
//lc = lastMoveCol

// no need to check blank with last move known
if (board[0][lc] == board[1][lc] && board[0][lc] == board[2][lc] ||
board[lr][0] == board[lr][1] && board[lr][0] == board[lr][2]){
// Game over
}

// Check diagonals
if (board[1][1] != blank &&
(board[0][0] == board[1][1] && board[0][0] == board[2][2] ||
board[2][0] == board[1][1] && board[2][0] == board[0][2])){
// Game over
}

或者 - 检查所有状态:

//Check horizontals and verticals at once
for (int i = 0; i < 3; ++i){
// Check column and row at once
if (board[0][i] != blank && board[0][i] == board[1][i] && board[0][i] == board[2][i] ||
board[i][0] != blank && board[i][0] == board[i][1] && board[i][0] == board[i][2]){
// Game over
}
}

// Check diagonals
if (board[1][1] != blank &&
(board[0][0] == board[1][1] && board[0][0] == board[2][2] ||
board[2][0] == board[1][1] && board[2][0] == board[0][2])){
// Game over
}

或者,如果您确实将它变成了一点一点的系统 - 保持单独的 X 和 O 板以便于更新。那么你只需要 9 位 x,9 位 O,你的获胜棋盘匹配就简单多了。 (在这种情况下要找到开放空间,只需按位或 x 和 o 板)

// winning 9 bit boards
// int winningBoards[8]
000000111
000111000
111000000
001001001
010010010
100100100
100010001
001010100

//xBoard and yBoard can be ints
for (int i = 0; i < 8; ++i){
if (xBoard & winningBoards[i] == winningBoards[i]){
//Game over
}
}

关于C++ - 连续检查 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2301125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com