#很久以前写的,终端输入坐标下棋,写博客是为了养成习惯,谢谢大家喜欢
#include <stdio.h>
#define SIZE 15
// 棋盘初始化
void initBoard(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = ' ';
}
}
}
// 打印棋盘
void printBoard(const char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%c", board[i][j]);
if (j < SIZE - 1) {
printf("|");
}
}
printf("\n");
if (i < SIZE - 1) {
for (int j = 0; j < SIZE; j++) {
printf("---");
}
printf("\n");
}
}
}
// 检查胜利条件
int checkWin(const char board[SIZE][SIZE], int x, int y, char player) {
// 横向、纵向、斜向检查是否有连续的五个棋子
for (int i = -4; i <= 4; i++) {
for (int j = -4; j <= 4; j++) {
if (i == 0 && j == 0) continue; // 跳过自己
int count = 0;
int XX = x + i;
int YY = y + j;
if ( XX >= 0 && XX < SIZE && YY >= 0 && YY < SIZE) {
if (board[ XX] [YY ] == player)
{
count++;
if (count == 5) {
return 1; // 胜利
}
} else {
count = 0;
}
}
}
}
return 0; // 未胜利
}
// 主函数
int main() {
char board[SIZE][SIZE];
char player = 'X'; // 玩家X先手
int turn = 0; // 当前回合数
initBoard(board);
printBoard(board);
while (1) {
printf("Player %c turn: ", player);
int x, y;
scanf("%d %d", &x, &y);
if (board[x][y] == ' ') {
board[x][y] = player;
printBoard(board);
if (checkWin(board, x, y, player)) {
printf("Player %c wins!\n", player);
break;
}
player = (player == 'X') ? 'O' : 'X'; // 切换玩家
turn++;
} else {
printf("Invalid move, try again.\n");
}
}
return 0;
}
一个非常非常简单的五子棋
最新推荐文章于 2024-07-13 19:27:27 发布