用c语言写一个五子棋游戏
时间: 2023-03-12 13:59:26 浏览: 50
好的,以下是一个简单的五子棋游戏的 C 语言代码。请注意,这个代码可能不是最优的,但它可以作为一个起点来理解五子棋游戏的实现方式。
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BOARD_SIZE 15 // 棋盘大小
typedef enum { // 定义棋子类型
EMPTY,
BLACK,
WHITE
} PieceType;
PieceType board[BOARD_SIZE][BOARD_SIZE]; // 棋盘
void print_board() { // 打印棋盘
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%c ", 'A' + i);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%2d", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
printf(" +");
} else if (board[i][j] == BLACK) {
printf(" x");
} else {
printf(" o");
}
}
printf("\n");
}
}
bool is_valid_move(int row, int col) { // 判断移动是否有效
return row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == EMPTY;
}
bool is_win(int row, int col, PieceType piece) { // 判断是否获胜
int count = 0;
for (int i = row - 4; i <= row + 4; i++) { // 横向判断
if (i < 0 || i >= BOARD_SIZE) continue;
if (board[i][col] == piece) {
count++;
if (count == 5) return true;
} else {
count = 0;
}
}
count = 0;
for (int j = col - 4; j <= col + 4; j++) { // 竖向判断
if (j < 0 || j >= BOARD_SIZE) continue;
if (board[row][j] == piece) {
count++;
if (count == 5) return true;
} else {
count = 0;
}
}
count = 0;
for (int i = row - 4, j = col - 4; i <= row + 4; i++, j++) { // 左上到右下判断
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) continue;
if (board[i][j] == piece) {
count++;
if (count == 5) return true;
} else {
count = 0;
}
}
count = 0;
for (int i = row - 4, j = col + 4; i <= row + 4; i++, j--) { // 右上到左下判断
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) continue;
if (board[i][j] == piece) {
count++;
if (count == 5) return true;
} else {
count = 0;
}
}
return
阅读全文