代码拉取完成,页面将自动刷新
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<time.h>
#define MAX_ROW 3
#define MAX_COL 3
//将棋盘初始化成' '
void init(char board[MAX_ROW][MAX_COL]) {
for (int row = 0; row < MAX_ROW; row++) {
for(int col = 0; col < MAX_COL; col++) {
board[row][col] = ' ';
}
}
//设计随机种子
srand((unsigned int) time(0));
}
void printBoard(char board[MAX_ROW][MAX_COL]) {
system("cls");
for (int row = 0; row < MAX_ROW; row++) {
printf("+---+---+---+\n");
for (int col = 0; col < MAX_COL; col++) {
printf("| %c ", board[row][col]);
}
printf("|");
printf("\n");
}
printf("+---+---+---+\n");
}
void playerMove(char board[MAX_ROW][MAX_COL]) {
printf("请玩家落子!");
while (1) {
printf("请输入落子的位置(row col):");
int row = 0;
int col = 0;
scanf("%d %d", &row, &col);
//输入后验证输入内容是否合法.
if (row < 0 || row >= MAX_ROW || col < 0 || col >= MAX_COL) {
printf("输入有误.请重新输入!\n");
continue;
}
if (board[row][col] != ' ') {
printf("当前位置已有棋子,请重新输入!\n");
continue;
}
board[row][col] = 'x';
break;
}
}
void computerMove(char board[MAX_ROW][MAX_COL]) {
printf("轮到电脑落子");
while (1) {
int row = rand() % MAX_ROW;
int col = rand() % MAX_COL;
if (board[row][col] != ' ') {
continue;
}
board[row][col] = 'o';
break;
}
}
int isFull(char board[MAX_ROW][MAX_COL]) {
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
if (board[row][col] == ' ') {
//棋盘没满
return 0;
}
}
}
return 1;
}
int checkWinner(char board[MAX_ROW][MAX_COL]) {
//检查所有行
for (int row = 0; row < MAX_ROW; row++) {
if (board[row][0] != ' ' && board[row][0] == board[row][1] && board[row][0] == board[row][2]) {
return board[row][0];
}
}
//检查所有列
for (int col = 0; col < MAX_COL; col++) {
if (board[0][col] != ' ' && board[0][col] == board[1][col] && board[0][col] == board[2][col]) {
return board[0][col];
}
}
//检查对角线
if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != ' ') {
return board[0][0];
}
if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != ' ') {
return board[0][2];
}
if (isFull(board)) {
return 'q';
}
return ' ';
}
int main() {
char winner = ' ';
//1.创建一个棋盘,并初始化.
char board[MAX_ROW][MAX_COL] = { 0 };
//2.init函数将棋盘每个格子初始化成' '.
init(board);
while (1) {
//3.打印棋盘
printBoard(board);
//4.玩家落子
playerMove(board);
//5.判断胜负
winner = checkWinner(board);
if (winner != ' ') {
//胜负已分
break;
}
//6.电脑落子
computerMove(board);
//7.判断胜负
winner = checkWinner(board);
if (winner != ' ') {
//胜负已分
break;
}
}
if (winner == 'x') {
printf("恭喜你,你赢了!\n");
}else if(winner=='o') {
printf("你真菜连人工智障都玩不过\n");
}else {
printf("你和人工智障五五开\n");
}
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。