基于极大极小算法和alpha-beta剪枝实现AI井字棋

2024-03-18 10:38

本文主要是介绍基于极大极小算法和alpha-beta剪枝实现AI井字棋,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于极大极小算法和alpha-beta剪枝可以参考文章的参考资料,这里仅对其进行代码实现。

其实这个算法单纯的理解并不容易,下面用代码进行实现。

说一下实现这个AI井字棋的思路:

简单的来说就是计算机希望估值函数值最大,而下棋人希望这个估值最小,因此在计算机决策是就用递归的向前看,这里的递归其实蛮不好理解的,但是可以宏观的去理解。

下面是代码的构成:

  1. 一个ChessBoard的类用来处理一些关于棋盘的事件。
  2. 一个TicTacToe的类用来实现游戏开始和计算机,玩家决策的事件

ChessBoard.h

//Author : yqtao
//Date   :2016.10.30
#ifndef CHESS_BOARD_H
#define CHESS_BOARD_H
#include<vector>
#include<iostream>
#include<string>
using namespace std;const int ChessBoard_Row = 13;
const int ChessBoard_Col = 26;
const int GridNuber = 9;
const char Comp_Char = 'X';
const char Human_Char = 'O';
const char Blank_Char = ' ';class ChessBoard {
public:ChessBoard();bool isEmpty(int pos);bool isFull();bool canWin(char c);bool immediateComWin(int& bestMove);bool immediateHumanWin(int& bestMove);void placeComp(int pos);void placeHuman(int pos);void unPlace(int pos);void print();
private:vector<char> boardInOneDimens;vector<string> board;};
#endif // !CHESS_BOARD_H

ChessBoard.cpp

#include"ChessBoard.h"
ChessBoard::ChessBoard() {             //默认构造函数boardInOneDimens.resize(GridNuber);for (int i = 0; i < GridNuber; i++)boardInOneDimens[i] = ' ';vector<string>tmp = {"- - - - - - - - - - - - -","|       |       |       |","|       |       |       |","|       |       |       |","- - - - - - - - - - - - -","|       |       |       |","|       |       |       |","|       |       |       |","- - - - - - - - - - - - -","|       |       |       |","|       |       |       |","|       |       |       |","- - - - - - - - - - - - -"};board = tmp;
}
//check the posion is empty or not 
bool ChessBoard::isEmpty(int pos) {return boardInOneDimens[pos] == ' ';
}
//
bool ChessBoard::isFull() {for (int i = 0; i < GridNuber; i++) {if (boardInOneDimens[i] == ' ')return false;}return true;
}
//
bool ChessBoard::canWin(char c) {//check every rowfor (int i = 0; i <= 6; i+=3) {if (boardInOneDimens[i] == c&&boardInOneDimens[i] == boardInOneDimens[i + 1] &&boardInOneDimens[i] == boardInOneDimens[i + 2])return true;}//check every colfor (int i = 0; i < 3; i++) {if (boardInOneDimens[i] == c&&boardInOneDimens[i] == boardInOneDimens[i + 3] &&boardInOneDimens[i] == boardInOneDimens[i + 6])return true;}//check every diagonalsif (boardInOneDimens[0] == c&&boardInOneDimens[4] == c&&boardInOneDimens[8] == c)return true;if (boardInOneDimens[2] == c&&boardInOneDimens[4] == c&&boardInOneDimens[6] == c)return true;return false;
}
//
bool ChessBoard::immediateComWin(int& bestMove) {for (int i = 0; i < GridNuber; i++) {if (isEmpty(i)) {boardInOneDimens[i] =Comp_Char;bool Win = canWin(Comp_Char); boardInOneDimens[i] = Blank_Char;   //backtraceingif (Win) {bestMove = i;return true;}}}return false;
}
//
bool ChessBoard::immediateHumanWin(int& bestMove) {for (int i = 0; i < GridNuber; i++) {if (isEmpty(i)) {boardInOneDimens[i] = Human_Char;bool Win = canWin(Human_Char);boardInOneDimens[i] = Blank_Char;   //backtraceingif (Win) {bestMove = i;return true;}}}return false;
}
//
void ChessBoard::placeComp(int pos) {boardInOneDimens[pos] = 'X';
}
//
void ChessBoard::placeHuman(int pos) {boardInOneDimens[pos] = 'O';
}
//
void ChessBoard::unPlace(int pos) {boardInOneDimens[pos] = ' ';
}
//
void ChessBoard::print() {int cnt = 0;for (int i = 2; i <= 10; i += 4) {for (int j = 4; j <= 20; j += 8) {board[i][j] = boardInOneDimens[cnt++];}}for (int i = 0; i < ChessBoard_Row; ++i) {cout << board[i] << endl;}
}

TicTacToe.h

#ifndef TICTACTOE_H
#define TICTACTOE_H
#include "ChessBoard.h"
enum Role { Human, Comp };
static const int CompWin = 2;
static const int Draw = 1;
static const int HumanWin = 0;
class TicTacToe {
public:void start();bool handleGameOver();bool gameIsOver(bool &draw, Role &win);Role chooseFirstPlace();void compPlace();int getBestMove();void humanPlace();int getPlacePosition();void findCompMove(int& bestMove,int& value, int alpha, int beta);void findHumanMove(int& bestMove,int& value, int alpha, int beta);
private:ChessBoard board;
};
#endif // !TicTacToe

TicTacToe.cpp

#include "TicTacToe.h"
void TicTacToe::start() {Role firstPlace = chooseFirstPlace();if (firstPlace == Comp) {  // Choose computer to be the firstcompPlace();}while (1) {board.print();if (handleGameOver()) break;humanPlace();board.print();if (handleGameOver()) break;compPlace();}
}
Role TicTacToe::chooseFirstPlace() {int choose;while (1) {cout << "who will place first" << endl;cout << "0 : human first " << endl;cout << "1 : computer first" << endl;cin >> choose;if (choose == 0 || choose == 1) {cout << endl;break;}elsecout << "error,please enter again" << endl;}return (Role)choose;
}
//
void TicTacToe::humanPlace() {int pos = getPlacePosition();board.placeHuman(pos);cout << "Your choice:" << endl;
}
//
int TicTacToe::getPlacePosition() {int m, n,pos;while (1) {cout << "It is your turn, please input where you want :" << endl;cout << "for example: 2 2 mean you want to add position 2 row,2 col:" << endl;cin >> m >> n;if (m < 0 || m>3 || n < 0 || n>3)cout << "error,please input again:" << endl;else {pos = (m - 1) * 3 + n - 1;if (board.isEmpty(pos))break;elsecout << "error,please input again:" << endl;}}return pos;
}
//
void TicTacToe::compPlace() {int bestMove = getBestMove();board.placeComp(bestMove);cout << "the computer choice is: " << endl;
}
int TicTacToe::getBestMove() {int bestMove = 0, value = 0;findCompMove(bestMove,value,HumanWin, CompWin);return bestMove;
}
void TicTacToe::findCompMove(int& bestMove,int &value, int alpha, int beta) {if (board.isFull())value = Draw;else if (board.immediateComWin(bestMove))value = CompWin;else {value = alpha;for (int i = 0; i < GridNuber&&value < beta; i++) {if (board.isEmpty(i)) {board.placeComp(i);int tmp = -1, response = -1;  // Tmp is uselessfindHumanMove(tmp, response, value, beta);board.unPlace(i);if (response > value) {value = response;bestMove = i;}}}}
}void TicTacToe::findHumanMove(int& bestMove,int & value, int alpha, int beta) {if (board.isFull())value=Draw;else if (board.immediateHumanWin(bestMove)){value=HumanWin;}else {value = beta; for (int i = 0; i < GridNuber&&value>alpha; i++) {if (board.isEmpty(i)) {board.placeHuman(i);int tmp = -1, response = -1;  // Tmp is uselessfindCompMove(tmp, response, alpha, value);board.unPlace(i);if (response <value) {value = response;bestMove = i;}}}}
}
//
bool TicTacToe::gameIsOver(bool &draw, Role &win) {if (board.canWin(Comp_Char)) {win =Comp ;draw = false;return true;}else if (board.canWin(Human_Char)) {win = Human;draw = false;return true;}else if (board.isFull()) {draw = true;return true;}else {return false;}
}bool TicTacToe::handleGameOver()  {bool draw = false;Role whoWin = Human;if (gameIsOver(draw, whoWin)) {if (draw) {cout << "Draw!" << endl;}else {if (whoWin == Comp) {cout << "You lose!" << endl;}else if (whoWin == Human) {cout << "Congratulations! You defeat the computer." << endl;}}return true;}else {return false;}
}

实现的结果如下图所示:

这里写图片描述

完成的代码和运行:

在Linux的环境下:

git clone https://github.com/yqtaowhu/DataStructureAndAlgorithm
cd DataStructureAndAlgorithm/Algorithm/TicTacToe/
make run

在window的环境下可用VS进行编译。
完整的代码在我的Github:
https://github.com/yqtaowhu/DataStructureAndAlgorithm/tree/master/Algorithm/TicTacToe

参考资料:
1. 数据结构与算法分析——C++语言描述
2. http://blog.csdn.net/tianranhe/article/details/8301756
3. http://blog.csdn.net/qq_22885773/article/details/50967021

这篇关于基于极大极小算法和alpha-beta剪枝实现AI井字棋的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/822077

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

揭秘未来艺术:AI绘画工具全面介绍

📑前言 随着科技的飞速发展,人工智能(AI)已经逐渐渗透到我们生活的方方面面。在艺术创作领域,AI技术同样展现出了其独特的魅力。今天,我们就来一起探索这个神秘而引人入胜的领域,深入了解AI绘画工具的奥秘及其为艺术创作带来的革命性变革。 一、AI绘画工具的崛起 1.1 颠覆传统绘画模式 在过去,绘画是艺术家们通过手中的画笔,蘸取颜料,在画布上自由挥洒的创造性过程。然而,随着AI绘画工

一份LLM资源清单围观技术大佬的日常;手把手教你在美国搭建「百万卡」AI数据中心;为啥大模型做不好简单的数学计算? | ShowMeAI日报

👀日报&周刊合集 | 🎡ShowMeAI官网 | 🧡 点赞关注评论拜托啦! 1. 为啥大模型做不好简单的数学计算?从大模型高考数学成绩不及格说起 司南评测体系 OpenCompass 选取 7 个大模型 (6 个开源模型+ GPT-4o),组织参与了 2024 年高考「新课标I卷」的语文、数学、英语考试,然后由经验丰富的判卷老师评判得分。 结果如上图所

AI儿童绘本创作

之前分享过AI儿童绘画的项目,但是主要问题是角色一致要花费很长的时间! 今天发现了这款,非常奈斯! 只需输入故事主题、风格、模板,软件就会自动创作故事内容,自动生成插画配图,自动根据模板生成成品,测试效果如下图。 变现方式:生成儿童绘本发布到各平台,吸引宝妈群体进私域。  百度网盘 请输入提取码百度网盘为您提供文件的网络备份、同步和分享服务。空间大、速度快、安全

通过SSH隧道实现通过远程服务器上外网

搭建隧道 autossh -M 0 -f -D 1080 -C -N user1@remotehost##验证隧道是否生效,查看1080端口是否启动netstat -tuln | grep 1080## 测试ssh 隧道是否生效curl -x socks5h://127.0.0.1:1080 -I http://www.github.com 将autossh 设置为服务,隧道开机启动

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

vue项目集成CanvasEditor实现Word在线编辑器

CanvasEditor实现Word在线编辑器 官网文档:https://hufe.club/canvas-editor-docs/guide/schema.html 源码地址:https://github.com/Hufe921/canvas-editor 前提声明: 由于CanvasEditor目前不支持vue、react 等框架开箱即用版,所以需要我们去Git下载源码,拿到其中两个主

代码随想录算法训练营:12/60

非科班学习算法day12 | LeetCode150:逆波兰表达式 ,Leetcode239: 滑动窗口最大值  目录 介绍 一、基础概念补充: 1.c++字符串转为数字 1. std::stoi, std::stol, std::stoll, std::stoul, std::stoull(最常用) 2. std::stringstream 3. std::atoi, std

android一键分享功能部分实现

为什么叫做部分实现呢,其实是我只实现一部分的分享。如新浪微博,那还有没去实现的是微信分享。还有一部分奇怪的问题:我QQ分享跟QQ空间的分享功能,我都没配置key那些都是原本集成就有的key也可以实现分享,谁清楚的麻烦详解下。 实现分享功能我们可以去www.mob.com这个网站集成。免费的,而且还有短信验证功能。等这分享研究完后就研究下短信验证功能。 开始实现步骤(新浪分享,以下是本人自己实现

基于Springboot + vue 的抗疫物质管理系统的设计与实现

目录 📚 前言 📑摘要 📑系统流程 📚 系统架构设计 📚 数据库设计 📚 系统功能的具体实现    💬 系统登录注册 系统登录 登录界面   用户添加  💬 抗疫列表展示模块     区域信息管理 添加物资详情 抗疫物资列表展示 抗疫物资申请 抗疫物资审核 ✒️ 源码实现 💖 源码获取 😁 联系方式 📚 前言 📑博客主页: