你是一个清华大学计算机的学生,请做一份c语言程序五子棋小游戏
时间: 2024-01-21 15:20:12 浏览: 28
好的,以下是一个简单的C语言五子棋小游戏程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 15
char board[SIZE][SIZE];
void init_board() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
board[i][j] = '.';
}
}
}
void print_board() {
int i, j;
printf("\n");
for (i = 0; i < SIZE; i++) {
printf("%2d ", i);
for (j = 0; j < SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
printf(" ");
for (i = 0; i < SIZE; i++) {
printf("%d ", i);
}
printf("\n");
}
int check_win(int x, int y) {
char c = board[x][y];
int i, j, cnt;
// check row
cnt = 0;
for (j = 0; j < SIZE; j++) {
if (board[x][j] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
cnt = 0;
}
}
// check column
cnt = 0;
for (i = 0; i < SIZE; i++) {
if (board[i][y] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
cnt = 0;
}
}
// check diagonal
cnt = 0;
for (i = x, j = y; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
break;
}
}
for (i = x+1, j = y+1; i < SIZE && j < SIZE; i++, j++) {
if (board[i][j] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
break;
}
}
// check anti-diagonal
cnt = 0;
for (i = x, j = y; i >= 0 && j < SIZE; i--, j++) {
if (board[i][j] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
break;
}
}
for (i = x+1, j = y-1; i < SIZE && j >= 0; i++, j--) {
if (board[i][j] == c) {
cnt++;
if (cnt == 5) return 1;
} else {
break;
}
}
return 0;
}
int main() {
int x, y, turn = 0;
init_board();
while (1) {
print_board();
if (turn % 2 == 0) {
printf("Player 1's turn (X)\n");
} else {
printf("Player 2's turn (O)\n");
}
printf("Enter the position (x, y): ");
scanf("%d%d", &x, &y);
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
printf("Invalid position!\n");
continue;
}
if (board[x][y] != '.') {
printf("This position is already occupied!\n");
continue;
}
board[x][y] = (turn % 2 == 0 ? 'X' : 'O');
if (check_win(x, y)) {
print_board();
if (turn % 2 == 0) {
printf("Player 1 (X) wins!\n");
} else {
printf("Player 2 (O) wins!\n");
}
break;
}
turn++;
}
return 0;
}
```
这个程序实现了一个基本的五子棋游戏,先让用户输入坐标,然后判断是否合法,如果合法则在棋盘上落子,并且判断是否胜利。如果胜利则输出获胜者,并结束游戏。