用C语言写一个五子棋游戏的代码
时间: 2024-10-13 22:11:17 浏览: 44
编写一个完整的五子棋游戏的C语言代码需要相当多的篇幅,这里我会给出一个简单的框架以及关键部分的代码示例,供你参考和继续扩展:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row;
int col;
} Point;
// 棋盘大小
#define BOARD_SIZE 15
char board[BOARD_SIZE][BOARD_SIZE]; // 棋盘数组
// 标记玩家1和玩家2的棋子
enum Player {PLAYER_X = 'X', PLAYER_O = 'O'};
Player currentPlayer = PLAYER_X;
void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%s", board[i]);
if (i % 5 == 4) printf("\n");
}
}
bool isValidMove(int row, int col) {
return row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == '\0';
}
// 玩家下棋函数
void makeMove(int row, int col) {
board[row][col] = currentPlayer;
}
// 判断是否形成五子连珠
bool checkWin(int player) {
// 这里仅给出判断一行、一列和对角线的简单示例,实际游戏中还需遍历更多方向
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][0] != '\0' && board[i][0] == player && board[i][1] == player && board[i][2] == player &&
board[i][3] == player && board[i][4] == player) {
return true;
}
if (board[0][i] != '\0' && board[0][i] == player && board[1][i] == player && board[2][i] == player &&
board[3][i] == player && board[4][i] == player) {
return true;
}
}
return false;
}
int main() {
initBoard(); // 初始化棋盘
while (!checkWin(PLAYER_X) && !checkWin(PLAYER_O)) {
printBoard();
int row, col;
printf("Player %c's turn. Enter row and column (0-14): ", currentPlayer == PLAYER_X ? 'X' : 'O');
scanf("%d%d", &row, &col);
if (isValidMove(row, col)) {
makeMove(row, col);
currentPlayer = currentPlayer == PLAYER_X ? PLAYER_O : PLAYER_X;
} else {
printf("Invalid move. Try again.\n");
}
}
printBoard();
return 0;
}
阅读全文