用c语言编写一个五子棋
时间: 2023-09-07 22:12:16 浏览: 83
一个用C语言编写的五子棋
5星 · 资源好评率100%
好的,以下是一个简单的五子棋 C 语言程序:
```c
#include <stdio.h>
#define BOARD_SIZE 15
char board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '+';
}
}
}
void print_board() {
int i, j;
printf(" ");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i + 1);
for (j = 0; j < BOARD_SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int check_win(int x, int y, char c) {
int i, j;
int count;
// 检查横向
count = 0;
for (i = x - 4; i <= x; i++) {
if (i < 0 || i + 4 >= BOARD_SIZE) {
continue;
}
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[y][j] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 检查纵向
count = 0;
for (i = y - 4; i <= y; i++) {
if (i < 0 || i + 4 >= BOARD_SIZE) {
continue;
}
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[j][x] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 检查左上到右下
count = 0;
for (i = x - 4, j = y - 4; i <= x && j <= y; i++, j++) {
if (i < 0 || i + 4 >= BOARD_SIZE || j < 0 || j + 4 >= BOARD_SIZE) {
continue;
}
count = 0;
for (int k = 0; k < 5; k++) {
if (board[j + k][i + k] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 检查左下到右上
count = 0;
for (i = x - 4, j = y + 4; i <= x && j >= y; i++, j--) {
if (i < 0 || i + 4 >= BOARD_SIZE || j >= BOARD_SIZE || j - 4 < 0) {
continue;
}
count = 0;
for (int k = 0; k < 5; k++) {
if (board[j - k][i + k] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
return 0;
}
int main() {
int x, y;
char c = 'X';
init_board();
print_board();
while (1) {
printf("请 %c 棋手输入坐标(x,y): ", c);
scanf("%d,%d", &x, &y);
if (board[y - 1][x - 1] != '+') {
printf("该位置已经有棋子了!\n");
continue;
}
board[y - 1][x - 1] = c;
print_board();
if (check_win(x - 1, y - 1, c)) {
printf("恭喜 %c 棋手获胜!\n", c);
break;
}
if (c == 'X') {
c = 'O';
} else {
c = 'X';
}
}
return 0;
}
```
注意:这只是一个简单的实现,还有很多可以改进的地方,比如:增加判断下棋位置是否越界的代码、增加判断和打印平局的代码、增加人机对战模式等等。
阅读全文