AI思考落子点

在之前我们已经实现计算权值了,现在要想让AI落子,应根据之前的计算结果使棋子落在分值最大点上。当然可能会出现多个分值相同的最大点,这时在其中随机取一个点落下即可。

  • chessData.h
typedef struct point{
  int row;
  int col;
} point_t;

//机器下棋
point_t actionAI(ChessData* data); 
  • chessData.cpp
#include <time.h>
#include <stdlib.h>
#include <vector>
point_t actionAI(ChessData* data){
  //计算评分
  calcScore(data);
  
  //找出最大分数位置
  int maxScore = 0;
  std::vector<std::pair<int, int>> maxPoints;
  
  int k = 0;
  
  for(int row = 0; row < BOARD_GRAD_SIZE; row++){
    for(int col = 0; col < BOARD_GRAD_SIZE; col++){
    
      //若该坐标为空
      if(data->chessMap[row][col] == 0){
        //找出最大数和坐标
        if(data->scoreMap[row][col] > maxScore){
          maxScore.clear();
          k = 0;
          maxScore.push_back(std::make_pair(row, col));
          k++;
        
        }else if(data->scoreMap[row][col] == maxScore){
          maxPoints.push_back(std::make_pair(row, col));
          k++;
        }
      }
    
    }
  }
  
  //如果有多个点随机落子
  srand((unsigned)time(0));
  int index = rend() % k;
  return maxPoints[index];
  
}

实现AI落子

  • main.cpp
void AI_GO(){
  point_t point = actionAI(&game);
  clickPosRow = point.row;
  clickPosCol = point.col;
  
  Sleep(1000);
  chessDown(clickPosRow, clickPosCol, CHESS_WHITE);
  updateGameMap(&game, clickPosRow, clickPosCol);
  
}
最后修改:2022 年 04 月 01 日
如果觉得我的文章对你有用,请随意赞赏