####################################五子棋####################################
今天不做题,今天玩游戏
话不多说,上源码
#include <stdio.h>
#include <stdlib.h>
#define BOARD_SIZE 15
#define EMPTY 0
#define BLACK 1
#define WHITE 2
int board[BOARD_SIZE][BOARD_SIZE]; // 棋盘
int turn = BLACK; // 当前轮到哪个玩家
// 初始化棋盘
void init_board() {
int i, j;
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
// 打印棋盘
void print_board() {
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] == EMPTY) {
printf(" .");
} else if (board[i][j] == BLACK) {
printf(" x");
} else if (board[i][j] == WHITE) {
printf(" o");
}
}
printf("\n");
}
}
// 判断是否有五子连珠
int is_win(int x, int y) {
int i, j, k;
int count;
// 判断横向
count = 1;
for (i = x - 1; i >= 0 && board[i][y] == board[x][y]; i--) {
count++;
}
for (i = x + 1; i < BOARD_SIZE && board[i][y] == board[x][y]; i++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断纵向
count = 1;
for (j = y - 1; j >= 0 && board[x][j] == board[x][y]; j--) {
count++;
}
for (j = y + 1; j < BOARD_SIZE && board[x][j] == board[x][y]; j++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断左上到右下
count = 1;
for (i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == board[x][y]; i--, j--) {
count++;
}
for (i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == board[x][y]; i++, j++) {
count++;
}
if (count >= 5) {
return 1;
}
// 判断左下到右上
count = 1;
for (i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == board[x][y]; i--, j++) {
count++;
}
for (i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == board[x][y]; i++, j--) {
count++;
}
if (count >= 5) {
return 1;
}
return 0;
}
// 落子
void play(int x, int y) {
if (board[x][y] != EMPTY) {
printf("这个位置已经有棋子了,请重新输入。\n");
return;
}
board[x][y] = turn;
if (is_win(x, y)) {
printf("恭喜玩家 %c 获胜!\n", turn == BLACK ? 'x' : 'o');
exit(0);
}
turn = turn == BLACK ? WHITE : BLACK;
}
int main() {
int x, y;
init_board();
while (1) {
print_board();
printf("玩家 %c 落子,请输入坐标(例如:b3):", turn == BLACK ? 'x' : 'o');
scanf("%c%d", &y, &x);
getchar(); // 读取换行符
x--;
y -= 'a';
play(x, y);
}
return 0;
}