发布时间:2023-05-24 19:00
# define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#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(\"请玩家落子\\n\");
while (1) {
printf(\"请输入落子的位置(row,col)\");
int row = 0, 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]) {
//轮到电脑落子
while (1) {
if (isFull(board)) {
break;
}
int row = rand() % max_row;
int col = rand() % max_col;
if (board[row][col] != \' \') {
//说明位置已经有子了
continue;
}
board[row][col] = \'o\';
printBoard(board);
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;
}
char checkWinner(char board[max_row][max_col]) {
//1.检测所有行
for (int row = 0; row < max_row; row++) {
if (board[row][0] != \' \' && board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
return board[row][0];
}
}
//2.检查所有列
for (int col = 0; col < max_col; col++) {
if (board[0][col] != \' \' && board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
return board[0][col];
}
}
//3.检查所有对角线
if (board[0][0] != \' \' && board[0][0] == board[1][1]
&& board[0][0] == board[2][2]
) {
return board[0][0];
}
if (board[2][0] != \' \' && board[2][0] == board[1][1]
&& board[2][0] == board[0][2]
) {
return board[2][0];
}
//4.检查是否和棋
if (isFull(board)) {
return \'q\';
}
return \' \';
}
int main() {
//1.初始化棋盘
char board[max_row][max_col] = { 0 };
init(board);
char winner = \' \';
// 2.打印棋盘
printBoard(board);
while (1) {
//玩家落子
playerMove(board);
//电脑落子
computerMove(board);
//判定胜负 玩家胜返回x,电脑胜返回\'o\',和棋返回\'q\',胜负未分返回\' \'
winner = checkWinner(board);
if (winner == \'x\') {
printf(\"玩家获胜\");
}
if (winner == \'o\') {
printf(\"电脑获胜\");
}
if (winner == \'q\') {
printf(\"和棋\");
}
if (winner != \' \') {
//胜负已分 结束游戏
break;
}
}
return 0;
}
基本的功能是ok的,但是还有一些地方有些小问题,就是判断结束的时候
人工智能轨道交通行业周刊-第3期(2022.6.20-6.26)
基于C++,OpenCV3以及SVM的手写数字识别系统的设计(从手写数字识别设计中认识SVM)
课程笔记-三维点云处理06 ——3D Object Detection(上)
Lab: File path traversal, traversal sequences stripped non-recursively 文件路径遍历,遍历非递归过滤的语句
人均月薪7.6万!腾讯一季度营收超千亿;突破 1nm!台积电祭出“半金属”取代硅材料;苹果与微软竞争再升温 | EA周报...