请编写一段C语言代码,实现简单的五子棋游戏
时间: 2023-07-16 11:17:32 浏览: 53
下面是一个简单的五子棋游戏的C语言代码,使用了二维数组来表示棋盘和玩家输入的坐标来落子:
```
#include <stdio.h>
#define BOARD_SIZE 15
char board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
// 初始化棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '+';
}
}
}
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++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int check_win(int x, int y) {
// 判断胜负
char c = board[x][y];
int count = 1;
// 横向
for (int i = y + 1; i < BOARD_SIZE && board[x][i] == c; i++) {
count++;
}
for (int i = y - 1; i >= 0 && board[x][i] == c; i--) {
count++;
}
if (count >= 5) {
return 1;
}
count = 1;
// 纵向
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == c; i++) {
count++;
}
for (int i = x - 1; i >= 0 && board[i][y] == c; i--) {
count++;
}
if (count >= 5) {
return 1;
}
count = 1;
// 左上-右下
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == c; i++, j++) {
count++;
}
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == c; i--, j--) {
count++;
}
if (count >= 5) {
return 1;
}
count = 1;
// 右上-左下
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == c; i--, j++) {
count++;
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == c; i++, j--) {
count++;
}
if (count >= 5) {
return 1;
}
return 0;
}
int main() {
int x, y;
char player = 'X';
init_board();
while (1) {
print_board();
printf("Player %c's turn\n", player);
printf("Enter the coordinates (e.g. A1): ");
scanf("%c%d", &y, &x);
x--;
y -= 'A';
getchar(); // 读取换行符
if (board[x][y] == '+') {
board[x][y] = player;
if (check_win(x, y)) {
printf("Player %c wins!\n", player);
break;
}
player = player == 'X' ? 'O' : 'X';
} else {
printf("Invalid move! Please try again.\n");
}
}
return 0;
}
```