用c语言写一个五子棋游戏源代码
时间: 2024-10-15 20:16:16 浏览: 33
C语言五子棋游戏源代码
以下是一个简单的C语言五子棋游戏源代码,仅供参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BOARD_SIZE 15
void init_board(int board[][BOARD_SIZE]) {
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
board[i][j] = 0;
}
}
}
void print_board(int board[][BOARD_SIZE]) {
int i, j;
printf(" ");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%c ", 'A' + i);
}
printf("\n");
for (i = 0; i < BOARD_SIZE; i++) {
printf("%2d ", i + 1);
for (j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == 0) {
printf("+ ");
} else if (board[i][j] == 1) {
printf("O ");
} else if (board[i][j] == 2) {
printf("X ");
}
}
printf("\n");
}
}
bool is_valid(int x, int y) {
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE;
}
bool is_win(int board[][BOARD_SIZE], int player, int x, int y) {
int i, j, count;
// 水平方向
count = 1;
for (i = x - 1; is_valid(i, y) && board[i][y] == player; i--, count++);
for (i = x + 1; is_valid(i, y) && board[i][y] == player; i++, count++);
if (count >= 5) return true;
// 垂直方向
count = 1;
for (j = y - 1; is_valid(x, j) && board[x][j] == player; j--, count++);
for (j = y + 1; is_valid(x, j) && board[x][j] == player; j++, count++);
if (count >= 5) return true;
// 左上到右下方向
count = 1;
for (i = x - 1, j = y - 1; is_valid(i, j) && board[i][j] == player; i--, j--, count++);
for (i = x + 1, j = y + 1; is_valid(i, j) && board[i][j] == player; i++, j++, count++);
if (count >= 5) return true;
// 右上到左下方向
count = 1;
for (i = x + 1, j = y - 1; is_valid(i, j) && board[i][j] == player; i++, j--, count++);
for (i = x - 1, j = y + 1; is_valid(i, j) && board[i][j] == player; i--, j++, count++);
if (count >= 5) return true;
return false;
}
int main() {
int board[BOARD_SIZE][BOARD_SIZE];
int player = 1;
int x, y;
init_board(board);
while (true) {
print_board(board);
printf("Player %d's turn: ", player);
scanf("%d %d", &x, &y);
if (!is_valid(x - 1, y - 1)) {
printf("Invalid position.\n");
continue;
}
if (board[x - 1][y - 1] != 0) {
printf("Position already occupied.\n");
continue;
}
board[x - 1][y - 1] = player;
if (is_win(board, player, x - 1, y - 1)) {
printf("Player %d wins!\n", player);
break;
}
player = player == 1 ? 2 : 1;
}
print_board(board);
return 0;
}
```
阅读全文