C语言井字棋代码加注释
时间: 2023-07-09 19:13:07 浏览: 168
c语言井字棋
以下是 C 语言井字棋代码加注释:
```
#include <stdio.h>
#define BOARD_SIZE 3 // 定义棋盘大小为3
int board[BOARD_SIZE][BOARD_SIZE]; // 存储棋盘的二维数组
void init_board() { // 初始化棋盘,将所有位置都设置为0
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
board[i][j] = 0;
}
}
}
void print_board() { // 打印棋盘
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == 0) {
printf("_ "); // 未下棋的位置用"_"表示
} else if (board[i][j] == 1) {
printf("X "); // 玩家1下的棋用"X"表示
} else if (board[i][j] == 2) {
printf("O "); // 玩家2下的棋用"O"表示
}
}
printf("\n");
}
}
int check_win(int player) { // 检查指定玩家是否胜利,player为1表示玩家1,player为2表示玩家2
int i, j, win;
// 检查每一行是否连成一线
for (i = 0; i < BOARD_SIZE; i++) {
win = 1;
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
}
// 检查每一列是否连成一线
for (i = 0; i < BOARD_SIZE; i++) {
win = 1;
for (j = 0; j < BOARD_SIZE; j++) {
if (board[j][i] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
}
// 检查对角线是否连成一线
win = 1;
for (i = 0; i < BOARD_SIZE; i++) {
if (board[i][i] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
// 检查反对角线是否连成一线
win = 1;
for (i = 0; i < BOARD_SIZE; i++) {
if (board[i][BOARD_SIZE - 1 - i] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
return 0; // 没有胜利返回0
}
int main() {
int i, j, row, col, player = 1, num_moves = 0;
init_board(); // 初始化棋盘
while (1) {
printf("Player %d's turn:\n", player);
print_board(); // 打印棋盘
printf("Enter row and column to place %c: ", player == 1 ? 'X' : 'O');
scanf("%d %d", &row, &col);
if (board[row][col] != 0) { // 如果该位置已有棋子,重新输入
printf("Invalid move, try again.\n");
continue;
}
board[row][col] = player; // 将棋子放入棋盘
if (check_win(player)) { // 检查是否胜利
printf("Player %d wins!\n", player);
print_board();
break;
}
num_moves++; // 记录下棋步数
if (num_moves == BOARD_SIZE * BOARD_SIZE) { // 如果下满了棋盘,宣布平局
printf("Draw!\n");
print_board();
break;
}
player = player == 1 ? 2 : 1; // 切换玩家
}
return 0;
}
```
注释中详细解释了每个函数和变量的作用,以及程序的流程。
阅读全文