C语言编个五子棋的游戏
时间: 2023-08-09 13:05:43 浏览: 76
C语言编写五子棋游戏
好的,以下是一个简单的五子棋游戏的 C 语言代码,供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BOARD_SIZE 15
#define BLACK 'X'
#define WHITE 'O'
#define EMPTY ' '
// 定义棋盘和当前玩家
char board[BOARD_SIZE][BOARD_SIZE];
char current_player;
// 初始化棋盘
void init_board()
{
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
// 显示棋盘
void display_board()
{
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%c ", i + 'A');
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%2d ", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 判断是否合法落子
bool is_valid_move(int row, int col)
{
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return false;
}
if (board[row][col] != EMPTY) {
return false;
}
return true;
}
// 判断是否胜利
bool is_win(int row, int col)
{
char player = board[row][col];
int count = 0;
// 水平方向
for (int i = col - 4; i <= col + 4; i++) {
if (i < 0 || i >= BOARD_SIZE) {
continue;
}
if (board[row][i] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 垂直方向
count = 0;
for (int i = row - 4; i <= row + 4; i++) {
if (i < 0 || i >= BOARD_SIZE) {
continue;
}
if (board[i][col] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 斜向方向
count = 0;
for (int i = row - 4, j = col - 4; i <= row + 4 && j <= col + 4; i++, j++) {
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) {
continue;
}
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 反斜向方向
count = 0;
for (int i = row - 4, j = col + 4; i <= row + 4 && j >= col - 4; i++, j--) {
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) {
continue;
}
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
return false;
}
// 交换当前玩家
void switch_player()
{
if (current_player == BLACK) {
current_player = WHITE;
} else {
current_player = BLACK;
}
}
// 主函数
int main()
{
int row, col;
init_board();
current_player = BLACK;
while (true) {
display_board();
printf("当前玩家:%c,请输入落子位置(例如 A1):", current_player);
scanf("%d%c", &row, &col);
col = col - 'A';
row--;
if (!is_valid_move(row, col)) {
printf("非法落子,请重新输入!\n");
continue;
}
board[row][col] = current_player;
if (is_win(row, col)) {
display_board();
printf("游戏结束,%c 玩家获胜!\n", current_player);
break;
}
switch_player();
}
return 0;
}
```
该代码实现了一个简单的五子棋游戏,玩家可以在命令行中输入落子位置,程序会自动判断是否合法,并在胜利时输出获胜玩家。
阅读全文