Untitled
unknown
c_cpp
2 years ago
2.1 kB
8
Indexable
#include <cstdlib>
#include <bits/stdc++.h>
#include "../state/state.hpp"
#include "./minimax.hpp"
/**
* @brief Randomly get a legal action
*
* @param state Now state
* @param depth You may need this for other policy
* @return Move
*/
Move Minimax::get_move(State *state, int depth, bool player){
if(!state->legal_actions.size())
state->get_legal_actions();
auto actions = state->legal_actions;
int value;
if(player == false){ //self是 0 白 先手
int max_value=INT_MIN, max;
for(int i=0; i<actions.size(); i++){
State *tmp;
tmp = state->next_state(actions[i]);
value = Minimax::minimax(tmp, depth-1, false);
if(value > max_value){
max_value = value;
max = i;
}
delete tmp;
}
return actions[max];
}
else{ //self是 1 黑 後手
int min_value=INT_MAX, min;
for(int i=0; i<actions.size(); i++){
State *tmp;
tmp = state->next_state(actions[i]);
value = Minimax::minimax(tmp, depth-1, true);
if(value < min_value){
min_value = value;
min = i;
}
delete tmp;
}
return actions[min];
}
}
int Minimax::minimax(State *state, int depth, bool ismax){
auto actions = state->legal_actions;
if(depth==0 || state->game_state==WIN || state->game_state==DRAW){
return state->evaluate();
}
if(ismax){
int best_value = INT_MIN;
int value;
for(int i=0; i<actions.size(); i++){
State *tmp;
tmp = state->next_state(actions[i]);
value = Minimax::minimax(tmp, depth-1, false);
best_value = std::max(best_value,value);
delete tmp;
}
return best_value;
}
else{
int best_value = INT_MAX;
int value;
for(int i=0; i<actions.size(); i++){
State *tmp;
tmp = state->next_state(actions[i]);
value = Minimax::minimax(tmp, depth-1, true);
best_value = std::min(best_value,value);
delete tmp;
}
return best_value;
}
}Editor is loading...