generic-min-max
Version:
This node.js module exports a generic min-max algorithm, alongside some implementations This package comes with full typescript support!
32 lines • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const math_1 = require("./utils/math");
const INITIAL_DEPTH = 0;
function minMax(game, maxDepth = 9) {
const { getAllNextStates, getHeuristic } = game;
if (maxDepth < INITIAL_DEPTH) {
throw new Error(`maxDepth ${maxDepth} is out of bounds`);
}
// recursion initial trigger
return getBestContinuation(game.initialState, 0, maxDepth);
// recursive minMax function
function getBestContinuation(state, currentDepth = 0, maxDepth = 0) {
if (currentDepth === maxDepth) {
return { state, evaluation: getHeuristic(state) };
}
else {
const allNextStates = getAllNextStates(state);
if (allNextStates.length === 0) {
return { state, evaluation: getHeuristic(state) };
}
const allNextContinuations = allNextStates.map((nextState) => (getBestContinuation(nextState, currentDepth + 1, maxDepth)));
const allNextEvaluations = allNextContinuations.map((nextEvaluation) => nextEvaluation.evaluation);
const bestEvaluationIndex = state.player1Turn ? math_1.getMaxIndex(allNextEvaluations) : math_1.getMinIndex(allNextEvaluations);
const bestEvaluation = allNextEvaluations[bestEvaluationIndex];
const bestContinuation = allNextContinuations[bestEvaluationIndex];
return currentDepth === 0 ? bestContinuation : { state, evaluation: bestEvaluation };
}
}
}
exports.default = minMax;
//# sourceMappingURL=minMax.js.map