用C语言写一个井字棋程序
时间: 2023-06-18 10:08:28 浏览: 110
以下是一个简单的井字棋程序的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
char board[3][3]; // 存储棋盘状态
void draw_board(); // 绘制棋盘
int check_winner(); // 判断胜者
int is_board_full(); // 判断棋盘是否已满
int main()
{
int player = 1; // 1 代表玩家 1,2 代表玩家 2
int row, col; // 玩家下棋的行列
int winner = 0; // 胜者
// 初始化棋盘
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
// 游戏开始
printf("Welcome to Tic Tac Toe!\n");
while (winner == 0 && !is_board_full()) {
draw_board();
printf("Player %d, enter a row (0-2): ", player);
scanf("%d", &row);
printf("Player %d, enter a column (0-2): ", player);
scanf("%d", &col);
if (board[row][col] != ' ') {
printf("This cell is already occupied. Please try again.\n");
continue;
}
if (player == 1) {
board[row][col] = 'X';
} else {
board[row][col] = 'O';
}
winner = check_winner();
if (winner == 1) {
printf("Player 1 wins!\n");
} else if (winner == 2) {
printf("Player 2 wins!\n");
}
player = (player == 1) ? 2 : 1;
}
if (winner == 0) {
printf("It's a tie!\n");
}
return 0;
}
void draw_board()
{
printf(" %c | %c | %c \n", board[0][0], board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[1][0], board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[2][0], board[2][1], board[2][2]);
}
int check_winner()
{
// 检查行
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
if (board[i][0] == 'X') {
return 1;
} else if (board[i][0] == 'O') {
return 2;
}
}
}
// 检查列
for (int j = 0; j < 3; j++) {
if (board[0][j] == board[1][j] && board[1][j] == board[2][j]) {
if (board[0][j] == 'X') {
return 1;
} else if (board[0][j] == 'O') {
return 2;
}
}
}
// 检查对角线
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
if (board[0][0] == 'X') {
return 1;
} else if (board[0][0] == 'O') {
return 2;
}
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
if (board[0][2] == 'X') {
return 1;
} else if (board[0][2] == 'O') {
return 2;
}
}
return 0; // 没有胜者
}
int is_board_full()
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return 0; // 棋盘未满
}
}
}
return 1; // 棋盘已满
}
```
这个程序实现了一个简单的井字棋游戏,玩家可以通过输入行和列来下棋,程序会检查胜者并输出结果。
阅读全文