用C语言实现井字棋
时间: 2024-01-21 11:09:19 浏览: 128
好的,下面是一个简单的井字棋的C语言实现:
```
#include <stdio.h>
// 定义棋盘大小
#define ROWS 3
#define COLS 3
// 定义棋子类型
#define EMPTY 0
#define X 1
#define O 2
// 初始化棋盘
void init_board(int board[][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = EMPTY;
}
}
}
// 打印棋盘
void print_board(int board[][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] == X) {
printf("X ");
} else if (board[i][j] == O) {
printf("O ");
} else {
printf("- ");
}
}
printf("\n");
}
}
// 判断是否有玩家获胜
int check_win(int board[][COLS], int player) {
int i, j;
for (i = 0; i < ROWS; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return 1;
}
}
for (j = 0; j < COLS; j++) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == player) {
return 1;
}
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return 1;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return 1;
}
return 0;
}
// 判断是否平局
int check_tie(int board[][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] == EMPTY) {
return 0;
}
}
}
return 1;
}
// 玩家下棋
void player_move(int board[][COLS]) {
int row, col;
printf("Enter row and column (1-3): ");
scanf("%d %d", &row, &col);
row--;
col--;
if (row < 0 || row >= ROWS || col < 0 || col >= COLS || board[row][col] != EMPTY) {
printf("Invalid move. Try again.\n");
player_move(board);
} else {
board[row][col] = X;
}
}
// AI下棋
void ai_move(int board[][COLS]) {
int row, col;
printf("AI's turn:\n");
// 简单的AI策略:随机下一个可行的位置
do {
row = rand() % ROWS;
col = rand() % COLS;
} while (board[row][col] != EMPTY);
board[row][col] = O;
}
int main() {
int board[ROWS][COLS];
init_board(board);
printf("Welcome to Tic-Tac-Toe!\n");
printf("You are playing as X, AI is playing as O.\n");
printf("Enter row and column numbers to make your move.\n");
printf("Here is the initial board:\n");
print_board(board);
while (1) {
player_move(board);
print_board(board);
if (check_win(board, X)) {
printf("Congratulations! You win!\n");
break;
}
if (check_tie(board)) {
printf("It's a tie!\n");
break;
}
ai_move(board);
print_board(board);
if (check_win(board, O)) {
printf("AI wins! Better luck next time.\n");
break;
}
if (check_tie(board)) {
printf("It's a tie!\n");
break;
}
}
return 0;
}
```
这个程序实现了一个简单的井字棋游戏,玩家使用 X 表示,AI使用 O 表示。玩家和AI轮流下棋,第一个在一行、一列或一条对角线上连成三个棋子的人获胜,如果棋盘填满了但没有人获胜,则为平局。
阅读全文