编写一个C语言程序,让两个人在计算机上玩井字游戏
时间: 2024-03-24 20:40:47 浏览: 54
以下是一个简单的 C 语言代码实现:
```c
#include <stdio.h>
// 定义井字游戏棋盘
char board[10] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
// 函数声明
void print_board();
int is_winner(char);
int is_board_full();
void player_move(char, char);
// 主程序
int main() {
printf("欢迎来到井字游戏!\n");
print_board();
char player1 = 'X';
char player2 = 'O';
while (1) {
player_move(player1, '1');
print_board();
if (is_winner(player1)) {
printf("玩家 %c 获胜!\n", player1);
break;
}
if (is_board_full()) {
printf("平局!\n");
break;
}
player_move(player2, '2');
print_board();
if (is_winner(player2)) {
printf("玩家 %c 获胜!\n", player2);
break;
}
if (is_board_full()) {
printf("平局!\n");
break;
}
}
return 0;
}
// 函数定义:打印棋盘
void print_board() {
printf(" %c | %c | %c \n", board[1], board[2], board[3]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[4], board[5], board[6]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[7], board[8], board[9]);
}
// 函数定义:判断是否胜利
int is_winner(char player) {
return (board[1] == player && board[2] == player && board[3] == player) ||
(board[4] == player && board[5] == player && board[6] == player) ||
(board[7] == player && board[8] == player && board[9] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[3] == player && board[6] == player && board[9] == player) ||
(board[1] == player && board[5] == player && board[9] == player) ||
(board[3] == player && board[5] == player && board[7] == player);
}
// 函数定义:判断棋盘是否已满
int is_board_full() {
int i;
for (i = 1; i <= 9; i++) {
if (board[i] == ' ') {
return 0;
}
}
return 1;
}
// 函数定义:玩家下棋
void player_move(char player, char player_no) {
int move;
while (1) {
printf("请玩家 %c (玩家%s) 下棋 (1-9): ", player, player_no);
scanf("%d", &move);
if (move >= 1 && move <= 9 && board[move] == ' ') {
board[move] = player;
break;
} else {
printf("无效的位置,请重新选择。\n");
}
}
}
```
玩家可以依次输入要下的位置,如下所示:
```
欢迎来到井字游戏!
| |
| |
| |
---+---+---
| |
| |
| |
---+---+---
| |
| |
| |
请玩家 X (玩家1) 下棋 (1-9): 1
X | |
| |
| |
---+---+---
| |
| |
| |
---+---+---
| |
| |
| |
请玩家 O (玩家2) 下棋 (1-9): 5
X | |
| |
| |
---+---+---
| |
O | |
| |
---+---+---
| |
| |
| |
请玩家 X (玩家1) 下棋 (1-9): 2
X | X |
| |
| |
---+---+---
| |
O | |
| |
---+---+---
| |
| |
| |
请玩家 O (玩家2) 下棋 (1-9): 3
X | X | O
| |
| |
---+---+---
| |
O | |
| |
---+---+---
| |
| |
| |
请玩家 X (玩家1) 下棋 (1-9): 9
X | X | O
| |
| |
---+---+---
| |
O | |
| |
---+---+---
| |
| | X
| |
玩家 X 获胜!
```
阅读全文