nord vpnnord vpn
Ad

AlphaBeta_jie

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
2.0 kB
1
Indexable
Never
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <cassert>
#include <cstdint>

#include "../state/state.hpp"
#include "./alphabeta.hpp"
#define INF 1e9


/**
 * @brief get a legal action by alphabeta
 * S
 * @param state Now state
 * @param depth You may need this for other policy
 * @return Move 
 */
int AlphaBeta::alphabeta(State *state, int dpth, int alpha, int beta, int player){
  if(player == 0 && state->game_state == WIN)
    return INF;
  if(player == 1 && state->game_state == WIN)
    return -INF;
  if(dpth == 0 || state->game_state == DRAW){
    return state->evaluate();
  }
  if(player == 0){
    int value = -INF;
    auto actions = state->legal_actions;
    for(auto it : actions){
      value = std::max(value, alphabeta(state->next_state(it), dpth - 1, alpha, beta, 1));
      alpha = std::max(alpha, value);
      if (alpha >= beta)
        break; // beta cut off
    }
    return value;
  }
  else{
    int value = INF;
    auto actions = state->legal_actions;
    for(auto it : actions){
      value = std::min(value, alphabeta(state->next_state(it), dpth - 1, alpha, beta, 0));
      beta = std::min(beta, value);
      if (beta <= alpha)
        break; // alpha cut off
    }
    return value;
  }
}

Move AlphaBeta::get_move(State *state, int depth){
  if(!state->legal_actions.size())
    state->get_legal_actions();
  int maxVal = -INF;
  int minVal = INF;
  auto actions = state->legal_actions;
  Move maxMove = actions[0], minMove = actions[0];
  for(auto it : actions){
    int val = alphabeta(state->next_state(it), depth, -INF, INF, state->next_state(it)->player);
    if(val > maxVal){
        maxVal = val;
        maxMove = it;
    }
    if(val < minVal){
        minVal = val;
        minMove = it;
    }
  }
  if(state->player == 0) // white plays first
    return maxMove;
  else
    return minMove; // Black
}

nord vpnnord vpn
Ad