用C语言写一个井字棋小游戏完整代码
时间: 2024-10-20 10:17:48 浏览: 29
创建一个简单的井字棋(Tic Tac Toe)游戏的C语言代码可能比较复杂,因为它涉及到用户界面交互和二维数组的操作。以下是一个基本的控制台版井字棋游戏的示例代码:
```c
#include <stdio.h>
#define SIZE 3
// 定义游戏板结构
typedef struct {
char board[SIZE][SIZE];
} TicTacToe;
// 清空游戏板
void clear_board(TicTacToe *game) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
game->board[i][j] = '\0';
}
}
// 判断某位置是否为空
int is_empty(int row, int col, TicTacToe *game) {
return game->board[row][col] == '\0';
}
// 打印游戏板
void print_board(const TicTacToe *game) {
for (int i = 0; i < SIZE; i++) {
printf("%c | %c | %c\n", game->board[i][0], game->board[i][1], game->board[i][2]);
if (i != SIZE - 1)
printf("---------\n");
}
}
// 下一步操作,玩家输入坐标
void move(char player, int row, int col, TicTacToe *game) {
if (is_empty(row, col, game)) {
game->board[row][col] = player;
} else {
printf("该位置已被占用,请重新选择。\n");
move(player, row, col, game);
}
}
int main() {
TicTacToe game;
clear_board(&game);
char player = 'X'; // 先手通常为X
char opponent = 'O';
while (!check_win(game.board, player) && !check_win(game.board, opponent)) { // 检查平局或胜利
print_board(&game);
printf("Player %c,请输入行和列(0-2): ", player);
int row, col;
scanf("%d %d", &row, &col);
move(player, row, col, &game);
if (player == 'X')
player = 'O';
else
player = 'X';
}
// 检查结果并打印最后的游戏状态
print_board(&game);
return 0;
}
// 检查胜利条件(横/竖/对角线)
int check_win(char board[][SIZE], char player) {
for (int i = 0; i < SIZE; i++) {
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player))
return 1;
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player ||
board[0][2] == player && board[1][1] == player && board[2][0] == player)
return 1;
// 如果没有胜利也没有平局,则返回0
return 0;
}
```
请注意,这只是一个基础版本,实际应用中可能需要添加错误处理、循环结束条件判断以及用户交互优化等功能。运行这个代码需要一个支持C编译器环境。
阅读全文