c语言写一个五子棋游戏
时间: 2023-08-25 18:36:59 浏览: 128
c语言设计五子棋游戏.doc
好的,以下是一个简单的五子棋游戏的 C 代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
char board[ROW][COL]; // 棋盘
char player1 = 'X'; // 玩家1棋子
char player2 = 'O'; // 玩家2棋子
// 初始化棋盘
void init_board() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = '+';
}
}
}
// 打印棋盘
void print_board() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 下棋
void play(char player) {
int x, y;
printf("%c's turn, please enter the coordinate(x y): ", player);
scanf("%d %d", &x, &y);
if (x < 0 || x >= ROW || y < 0 || y >= COL) {
printf("The coordinate is invalid!\n");
play(player);
return;
}
if (board[x][y] != '+') {
printf("The coordinate has been occupied!\n");
play(player);
return;
}
board[x][y] = player;
}
// 判断是否胜利
int check_win(char player) {
int i, j, count;
// 检查行
for (i = 0; i < ROW; i++) {
count = 0;
for (j = 0; j < COL; j++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return 1;
}
} else {
count = 0;
}
}
}
// 检查列
for (j = 0; j < COL; j++) {
count = 0;
for (i = 0; i < ROW; i++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return 1;
}
} else {
count = 0;
}
}
}
// 检查左斜线
for (i = 0; i < ROW - 4; i++) {
for (j = 0; j < COL - 4; j++) {
if (board[i][j] == player && board[i+1][j+1] == player && board[i+2][j+2] == player && board[i+3][j+3] == player && board[i+4][j+4] == player) {
return 1;
}
}
}
// 检查右斜线
for (i = 0; i < ROW - 4; i++) {
for (j = 4; j < COL; j++) {
if (board[i][j] == player && board[i+1][j-1] == player && board[i+2][j-2] == player && board[i+3][j-3] == player && board[i+4][j-4] == player) {
return 1;
}
}
}
return 0;
}
int main() {
int round = 0;
init_board();
print_board();
while (1) {
if (round % 2 == 0) {
play(player1);
} else {
play(player2);
}
print_board();
if (check_win(player1)) {
printf("%c win!\n", player1);
break;
}
if (check_win(player2)) {
printf("%c win!\n", player2);
break;
}
if (round == ROW * COL) {
printf("Tie!\n");
break;
}
round++;
}
return 0;
}
```
这个程序会在控制台上显示一个 15x15 的棋盘,玩家可以输入坐标下棋,程序会不断检查是否有一方胜利或者平局。
阅读全文