帮我用c语言写井字棋游戏
时间: 2023-03-28 16:03:42 浏览: 107
好的,我可以帮您用 C 语言编写井字棋游戏。以下是代码示例:
#include <stdio.h>
char board[3][3]; // 井字棋棋盘
void init_board() { // 初始化棋盘
int i, j;
for (i = ; i < 3; i++) {
for (j = ; j < 3; j++) {
board[i][j] = ' ';
}
}
}
void print_board() { // 打印棋盘
int i, j;
for (i = ; i < 3; i++) {
printf(" %c | %c | %c \n", board[i][], board[i][1], board[i][2]);
if (i != 2) {
printf("---|---|---\n");
}
}
}
int check_win(char player) { // 检查是否获胜
int i;
for (i = ; i < 3; i++) {
if (board[i][] == player && board[i][1] == player && board[i][2] == player) {
return 1;
}
if (board[][i] == player && board[1][i] == player && board[2][i] == player) {
return 1;
}
}
if (board[][] == player && board[1][1] == player && board[2][2] == player) {
return 1;
}
if (board[][2] == player && board[1][1] == player && board[2][] == player) {
return 1;
}
return ;
}
void play_game() { // 开始游戏
int row, col;
char player = 'X';
int count = ;
init_board();
printf("游戏开始!\n");
print_board();
while (1) {
printf("玩家 %c,请输入行号和列号(例如:1 2):", player);
scanf("%d %d", &row, &col);
if (row < 1 || row > 3 || col < 1 || col > 3) {
printf("输入错误,请重新输入!\n");
continue;
}
if (board[row-1][col-1] != ' ') {
printf("该位置已经有棋子,请重新输入!\n");
continue;
}
board[row-1][col-1] = player;
count++;
print_board();
if (check_win(player)) {
printf("玩家 %c 获胜!\n", player);
break;
}
if (count == 9) {
printf("平局!\n");
break;
}
player = (player == 'X') ? 'O' : 'X';
}
}
int main() {
play_game();
return ;
}
阅读全文