用c编写一个五子棋程序
时间: 2024-05-11 13:20:27 浏览: 8
下面是一个简单的五子棋程序示例,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BOARD_SIZE 15
char board[BOARD_SIZE][BOARD_SIZE];
// 清空棋盘
void clear_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("%d ", i + 1);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%c ", i + 'A');
for (int j = 0; j < BOARD_SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 判断是否有五子连珠
bool check_win(int x, int y) {
char player = board[x][y];
int count = 1;
// 横向检查
for (int i = y - 1; i >= 0 && board[x][i] == player; i--) {
count++;
}
for (int i = y + 1; i < BOARD_SIZE && board[x][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 纵向检查
count = 1;
for (int i = x - 1; i >= 0 && board[i][y] == player; i--) {
count++;
}
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 左上-右下检查
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// 右上-左下检查
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
int main() {
clear_board();
print_board();
int x, y;
char player = 'O';
while (true) {
printf("Player %c's turn, enter move (e.g. A1): ", player);
scanf("%c%d", &x, &y);
getchar(); // 消耗多余的换行符
x -= 'A'; // 将字符转换为数字
y--;
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
printf("Invalid move, please try again.\n");
continue;
}
if (board[x][y] != '+') {
printf("That cell is already occupied, please try again.\n");
continue;
}
board[x][y] = player;
print_board();
if (check_win(x, y)) {
printf("Player %c wins!\n", player);
break;
}
// 切换到另一个玩家
player = (player == 'O') ? 'X' : 'O';
}
return 0;
}
```
这个程序实现了一个简单的五子棋游戏,可以在终端中运行。玩家轮流输入坐标进行下棋,程序会判断是否有五子连珠,如果有则输出胜利信息并结束游戏。