c语言写一个五子棋游戏
时间: 2023-09-11 22:06:29 浏览: 41
以下是一个简单的五子棋游戏的C语言代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 15
#define EMPTY 0
#define BLACK 1
#define WHITE 2
int board[SIZE][SIZE];
void init_board() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void print_board() {
int i, j;
printf(" ");
for (i = 0; i < SIZE; i++) {
printf("%2d", i);
}
printf("\n");
for (i = 0; i < SIZE; i++) {
printf("%2d", i);
for (j = 0; j < SIZE; j++) {
switch (board[i][j]) {
case EMPTY:
printf(" .");
break;
case BLACK:
printf(" *");
break;
case WHITE:
printf(" O");
break;
}
}
printf("\n");
}
}
int is_valid(int x, int y) {
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
return 0;
}
if (board[x][y] != EMPTY) {
return 0;
}
return 1;
}
int check(int x, int y, int color) {
int i, j, t;
int count = 1;
// 横向
for (i = x + 1; i < SIZE && board[i][y] == color; i++, count++);
for (i = x - 1; i >= 0 && board[i][y] == color; i--, count++);
if (count >= 5) {
return 1;
}
// 纵向
for (i = y + 1, count = 1; i < SIZE && board[x][i] == color; i++, count++);
for (i = y - 1; i >= 0 && board[x][i] == color; i--, count++);
if (count >= 5) {
return 1;
}
// 斜向(左上右下)
for (i = x + 1, j = y + 1, count = 1; i < SIZE && j < SIZE && board[i][j] == color; i++, j++, count++);
for (i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == color; i--, j--, count++);
if (count >= 5) {
return 1;
}
// 斜向(左下右上)
for (i = x + 1, j = y - 1, count = 1; i < SIZE && j >= 0 && board[i][j] == color; i++, j--, count++);
for (i = x - 1, j = y + 1; i >= 0 && j < SIZE && board[i][j] == color; i--, j++, count++);
if (count >= 5) {
return 1;
}
return 0;
}
int main() {
int x, y;
int color = BLACK;
init_board();
print_board();
while (1) {
printf("请输入落子位置(x y): ");
scanf("%d%d", &x, &y);
if (!is_valid(x, y)) {
printf("无效的位置!\n");
continue;
}
board[x][y] = color;
print_board();
if (check(x, y, color)) {
printf("恭喜,%s方胜利!\n", color == BLACK ? "黑" : "白");
break;
}
color = 3 - color; // 切换对手
}
return 0;
}
```
此代码实现了一个简单的五子棋游戏,规则如下:
1. 棋盘大小为15x15;
2. 玩家以黑色(*)和白色(O)两种颜色进行对弈;
3. 每次玩家输入落子位置,如果该位置已经有棋子或者越界,则提示无效位置;
4. 当一方落子后,判断是否胜利,如果胜利则输出胜利信息并结束游戏;
5. 如果没有胜利,则切换对手,继续游戏。