用c语言判断井字棋输赢
时间: 2023-12-17 22:02:47 浏览: 141
判断井字棋输赢可以使用C语言编写一个函数来实现。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdbool.h>
bool check_winner(char board[3][3], char player) {
// Check for horizontal wins
for (int row = 0; row < 3; row++) {
if (board[row][0] == player && board[row][1] == player && board[row][2] == player) {
return true;
}
}
// Check for vertical wins
for (int col = 0; col < 3; col++) {
if (board[0][col] == player && board[1][col] == player && board[2][col] == player) {
return true;
}
}
// Check for diagonal wins
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true;
}
return false;
}
int main() {
char board[3][3] = {
{'X', 'O', 'O'},
{'X', 'X', 'O'},
{'O', 'X', 'X'}
};
if (check_winner(board, 'X')) {
printf("X is the winner!\n");
} else if (check_winner(board, 'O')) {
printf("O is the winner!\n");
} else {
printf("No winner yet.\n");
}
return 0;
}
```
在上面的示例代码中,我们定义了一个 `check_winner` 函数,它接受一个二维字符数组 `board` 和一个字符 `player` 作为参数,表示当前玩家。该函数会遍历整个棋盘,检查是否存在横向、纵向或对角线上连续三个相同的棋子,如果有,就返回 `true`,表示当前玩家获胜。否则,返回 `false`,表示当前没有胜者。
在 `main` 函数中,我们定义了一个包含已下好的棋子的棋盘数组,然后调用 `check_winner` 函数来检查是否存在获胜者,如果有,就输出胜者的信息。
阅读全文