C语言五子棋项目架构示例
时间: 2024-01-04 09:04:27 浏览: 31
C语言五子棋项目的架构示例如下:
1. 定义棋盘数据结构和相关函数:
```c
#define BOARD_SIZE 15
typedef enum {EMPTY, BLACK, WHITE} Piece;
typedef struct {
Piece board[BOARD_SIZE][BOARD_SIZE];
} ChessBoard;
void initBoard(ChessBoard* board);
void printBoard(ChessBoard* board);
int isWin(ChessBoard* board, int row, int col, Piece piece);
```
2. 实现棋盘初始化函数和打印函数:
```c
void initBoard(ChessBoard* board) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board->board[i][j] = EMPTY;
}
}
}
void printBoard(ChessBoard* board) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
switch (board->board[i][j]) {
case EMPTY:
printf(".");
break;
case BLACK:
printf("X");
break;
case WHITE:
printf("O");
break;
}
}
printf("\n");
}
}
```
3. 实现判断胜利的函数:
```c
int isWin(ChessBoard* board, int row, int col, Piece piece) {
int count = 1;
int i, j;
// 横向判断
i = row;
j = col - 1;
while (j >= 0 && board->board[i][j] == piece) {
count++;
j--;
}
j = col + 1;
while (j < BOARD_SIZE && board->board[i][j] == piece) {
count++;
j++;
}
if (count >= 5) {
return 1;
}
// 纵向判断
count = 1;
i = row - 1;
j = col;
while (i >= 0 && board->board[i][j] == piece) {
count++;
i--;
}
i = row + 1;
while (i < BOARD_SIZE && board->board[i][j] == piece) {
count++;
i++;
}
if (count >= 5) {
return 1;
}
// 斜向判断
count = 1;
i = row - 1;
j = col - 1;
while (i >= 0 && j >= 0 && board->board[i][j] == piece) {
count++;
i--;
j--;
}
i = row + 1;
j = col + 1;
while (i < BOARD_SIZE && j < BOARD_SIZE && board->board[i][j] == piece) {
count++;
i++;
j++;
}
if (count >= 5) {
return 1;
}
// 反斜向判断
count = 1;
i = row - 1;
j = col + 1;
while (i >= 0 && j < BOARD_SIZE && board->board[i][j] == piece) {
count++;
i--;
j++;
}
i = row + 1;
j = col - 1;
while (i < BOARD_SIZE && j >= 0 && board->board[i][j] == piece) {
count++;
i++;
j--;
}
if (count >= 5) {
return 1;
}
return 0;
}
```