五子棋C语言实现
时间: 2023-08-20 17:14:41 浏览: 55
好的,下面是五子棋的C语言实现示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BOARD_SIZE 15
#define EMPTY 0
#define BLACK 1
#define WHITE 2
int board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
memset(board, EMPTY, sizeof(board));
}
void print_board() {
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i);
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
printf("+ ");
} else if (board[i][j] == BLACK) {
printf("X ");
} else {
printf("O ");
}
}
printf("\n");
}
}
int check_win(int player) {
int i, j, k, count;
// check row
for (i = 0; i < BOARD_SIZE; i++) {
count = 0;
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == player) {
count++;
if (count == 5) return 1;
} else {
count = 0;
}
}
}
// check column
for (j = 0; j < BOARD_SIZE; j++) {
count = 0;
for (i = 0; i < BOARD_SIZE; i++) {
if (board[i][j] == player) {
count++;
if (count == 5) return 1;
} else {
count = 0;
}
}
}
// check diagonal (upper part)
for (k = 0; k < BOARD_SIZE; k++) {
count = 0;
for (i = k, j = 0; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
if (board[i][j] == player) {
count++;
if (count == 5) return 1;
} else {
count = 0;
}
}
}
// check diagonal (lower part)
for (k = 1; k < BOARD_SIZE; k++) {
count = 0;
for (i = 0, j = k; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
if (board[i][j] == player) {
count++;
if (count == 5) return 1;
} else {
count = 0;
}
}
}
return 0;
}
void play_game() {
int player = BLACK;
int row, col;
while (1) {
printf("Player %d's turn:\n", player);
printf("Enter row and column (e.g. 3 4): ");
scanf("%d %d", &row, &col);
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
printf("Invalid input, please try again.\n");
continue;
}
if (board[row][col] != EMPTY) {
printf("This position is already occupied, please try again.\n");
continue;
}
board[row][col] = player;
print_board();
if (check_win(player)) {
printf("Player %d wins!\n", player);
return;
}
player = (player == BLACK) ? WHITE : BLACK;
}
}
int main() {
init_board();
print_board();
play_game();
return 0;
}
```
这段代码实现了基本的五子棋游戏功能,包括了初始化棋盘、打印棋盘、检查胜利条件、玩家轮流落子等功能。您可以根据自己的需求进行修改和完善。