加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
japplet.c 2.84 KB
一键复制 编辑 原始数据 按行查看 历史
luo 提交于 2021-10-18 23:07 . 三子棋
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化