c语言五子棋代码
时间: 2023-08-12 11:20:14 浏览: 92
以下是一个简单的 C 语言五子棋代码,供参考:
```c
#include <stdio.h>
#define ROWS 15
#define COLS 15
char board[ROWS][COLS]; // 棋盘
void init_board() { // 初始化棋盘
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = '+';
}
}
}
void print_board() { // 打印棋盘
int i, j;
printf(" ");
for (i = 0; i < COLS; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%d ", i);
for (j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int check_win(char c) { // 检查是否有五子连珠
int i, j;
// 横向
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS - 4; j++) {
if (board[i][j] == c &&
board[i][j+1] == c &&
board[i][j+2] == c &&
board[i][j+3] == c &&
board[i][j+4] == c) {
return 1;
}
}
}
// 竖向
for (i = 0; i < ROWS - 4; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] == c &&
board[i+1][j] == c &&
board[i+2][j] == c &&
board[i+3][j] == c &&
board[i+4][j] == c) {
return 1;
}
}
}
// 斜向
for (i = 0; i < ROWS - 4; i++) {
for (j = 0; j < COLS - 4; j++) {
if (board[i][j] == c &&
board[i+1][j+1] == c &&
board[i+2][j+2] == c &&
board[i+3][j+3] == c &&
board[i+4][j+4] == c) {
return 1;
}
}
}
for (i = 0; i < ROWS - 4; i++) {
for (j = 4; j < COLS; j++) {
if (board[i][j] == c &&
board[i+1][j-1] == c &&
board[i+2][j-2] == c &&
board[i+3][j-3] == c &&
board[i+4][j-4] == c) {
return 1;
}
}
}
return 0;
}
int main() {
int x, y;
int player = 1;
init_board();
while (1) {
print_board();
printf("Player %d's turn, please enter coordinate (x,y): ", player);
scanf("%d,%d", &x, &y);
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
printf("Invalid coordinate, please try again.\n");
continue;
}
if (board[x][y] != '+') {
printf("The coordinate has been occupied, please try again.\n");
continue;
}
if (player == 1) {
board[x][y] = 'O';
} else {
board[x][y] = 'X';
}
if (check_win(board[x][y])) {
print_board();
printf("Player %d wins!\n", player);
break;
}
player = 3 - player; // 切换玩家
}
return 0;
}
```
这个代码实现了一个简单的控制台五子棋游戏,玩家通过输入坐标来下棋,程序会检查是否有五子连珠,有则宣布该玩家获胜。
阅读全文