C语言实现的三子棋游戏
好的,下面是一个使用C语言实现的简单三子棋(井字棋)游戏代码示例。该游戏允许两个玩家在控制台轮流下棋,直到其中一方获胜或游戏平局。
#include <stdio.h>
#define SIZE 3
void initializeBoard(char board[SIZE][SIZE]);
void printBoard(char board[SIZE][SIZE]);
int checkWin(char board[SIZE][SIZE]);
int isBoardFull(char board[SIZE][SIZE]);
int main() {
char board[SIZE][SIZE];
int currentPlayer = 1;
int row, col;
int winner = 0;
initializeBoard(board);
while (!winner && !isBoardFull(board)) {
printBoard(board);
printf("Player %d's turn. Enter row and column (1-3, space-separated): ", currentPlayer);
scanf("%d %d", &row, &col);
row--; // Adjust for 0-based index
col--;
if (row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == ' ') {
board[row][col] = (currentPlayer == 1) ? 'X' : 'O';
winner = checkWin(board);
if (winner) {
printBoard(board);
printf("Player %d wins!\n", currentPlayer);
} else if (isBoardFull(board)) {
printBoard(board);
printf("It's a draw!\n");
} else {
currentPlayer = (currentPlayer == 1) ? 2 : 1;
}
} else {
printf("Invalid move. Try again.\n");
}
}
return 0;
}
void initializeBoard(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = ' ';
}
}
}
void printBoard(char board[SIZE][SIZE]) {
printf("\n");
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) printf("---+---+---\n");
}
printf("\n");
}
int checkWin(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
return 1;
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
return 1;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
return 1;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
return 1;
return 0;
}
int isBoardFull(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == ' ')
return 0;
}
}
return 1;
}
说明
初始化棋盘:
initializeBoard
函数将棋盘初始化为空格,以表示未被占据的位置。打印棋盘:
printBoard
函数在控制台中以井字棋格式显示当前棋盘状态。检查胜利条件:
checkWin
函数检查是否存在获胜的三连子,无论是行、列或对角线。检查棋盘是否满:
isBoardFull
函数检查棋盘是否还有空位,以判断平局。主逻辑:使用
while
循环,实现玩家轮流输入行列,放置棋子并检查胜利或平局情况。
你可以复制这段代码,在你的编译器中运行,并根据需要进行调整和扩展。希望这对你有帮助!