用C语言写一个井字游戏
时间: 2023-03-22 11:02:25 浏览: 83
很高兴能够回答你的问题,用C语言写一个井字游戏,可以参考以下代码:#include<stdio.h>
#include<stdlib.h>int main()
{
int i, j;
char board[3][3];
char turn;
// 初始化棋盘
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
board[i][j] = ' ';
// 游戏开始,先手为'X'
turn = 'X';
while (1) {
// 打印棋盘
printf("\n");
printf(" %c | %c | %c ", board[0][0], board[0][1], board[0][2]);
printf("\n---+---+---\n");
printf(" %c | %c | %c ", board[1][0], board[1][1], board[1][2]);
printf("\n---+---+---\n");
printf(" %c | %c | %c \n", board[2][0], board[2][1], board[2][2]);
// 获取落子位置
int row, col;
printf("\n轮到 %c 了. 请输入你要下的位置 (行 列): ", turn);
scanf("%d%d", &row, &col);
// 如果该位置已经有棋子存在,则重新输入
if (board[row][col] != ' ') {
printf("\n错误:该位置已经有棋子存在!\n");
continue;
}
// 将棋子放到棋盘上
board[row][col] = turn;
// 判断输赢
if ((board[0][0] == turn && board[0][1] == turn && board[0][2] == turn) ||
(board[1][0] == turn && board[1][1] == turn && board[1][2] == turn) ||
(board[2][0] == turn && board[2][1] == turn && board[2][2] == turn) ||
(board[0][0] == turn && board[1][0] == turn && board[2][0] == turn) ||
(board[0][1] == turn && board[1][1] == turn && board[2][1] == turn) ||
(board[0][2] == turn && board[1][2] == turn && board[2][2] == turn) ||
(board[0][0] == turn && board[1][1] == turn && board[2][2] == turn) ||
(board[2][0] == turn && board[1][1] == turn && board[0][2] == turn)) {
printf("\n恭喜,%c 赢了!\n", turn);
break;
}
// 判断平局
int flag = 0;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (board[i][j] == ' ')
flag = 1;
if (flag == 0) {
printf("\n哈哈,平局!\n");
break;
}
// 切换回合
if (turn == 'X')
turn = 'O';
else
turn = 'X';
}
return 0;
}
阅读全文