帮我用C语言写一个五子棋游戏
时间: 2023-05-21 09:02:11 浏览: 109
好的,以下是一个简单的五子棋游戏的 C 语言代码:
#include <stdio.h>
#include <stdlib.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("%2d", i + 1);
}
printf("\n");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%2d", i + 1);
for (j = 0; j < BOARD_SIZE; j++) {
printf("%2c", board[i][j]);
}
printf("\n");
}
}
int check_win(int x, int y, char c) {
int i, j, 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, turn = 0;
char c;
init_board();
while (1) {
print_board();
if (turn % 2 == 0) {
c = 'X';
} else {
c = 'O';
}
printf("Player %c's turn, please enter the coordinate (x y): ", c);
scanf("%d %d", &x, &y);
if (x < 1 || x > BOARD_SIZE || y < 1 || y > BOARD_SIZE) {
printf("Invalid coordinate, please try again.\n");
continue;
}
if (board[y - 1][x - 1] != ' ') {
printf("This position has been occupied, please try again.\n");
continue;
}
board[y - 1][x - 1] = c;
if (check_win(x - 1, y - 1, c)) {
printf("Player %c wins!\n", c);
break;
}
turn++;
}
print_board();
return 0;
}
阅读全文