我使用chessBoard[][]二维数组存放棋盘上的棋子,0表示该点没有棋子,1表示白子,-1表示黑子;请用C++给我判断输赢的代码
时间: 2024-01-02 08:02:46 浏览: 86
d3-chessboard:只是一个D3棋盘
以下是使用连通性算法判断输赢的C++代码实现:
```c++
// 判断某个位置的棋子是否连成五个
bool checkWin(int chessBoard[][15], int row, int col) {
int chess = chessBoard[row][col];
int count = 1;
// 判断横向
for (int i = col - 1; i >= 0; i--) {
if (chessBoard[row][i] == chess) {
count++;
} else {
break;
}
}
for (int i = col + 1; i < 15; i++) {
if (chessBoard[row][i] == chess) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断竖向
count = 1;
for (int i = row - 1; i >= 0; i--) {
if (chessBoard[i][col] == chess) {
count++;
} else {
break;
}
}
for (int i = row + 1; i < 15; i++) {
if (chessBoard[i][col] == chess) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断左斜
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessBoard[i][j] == chess) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col + 1; i < 15 && j < 15; i++, j++) {
if (chessBoard[i][j] == chess) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断右斜
count = 1;
for (int i = row - 1, j = col + 1; i >= 0 && j < 15; i--, j++) {
if (chessBoard[i][j] == chess) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col - 1; i < 15 && j >= 0; i++, j--) {
if (chessBoard[i][j] == chess) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
// 判断胜负
int checkWinner(int chessBoard[][15]) {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (chessBoard[i][j] != 0) {
if (checkWin(chessBoard, i, j)) {
return chessBoard[i][j];
}
}
}
}
return 0;
}
```
在以上代码中,checkWin函数用来判断某个位置的棋子是否连成五个;checkWinner函数用来遍历整个棋盘,判断胜负。函数返回值为1表示白方胜利,-1表示黑方胜利,0表示平局。
阅读全文