Game Tree Visualiser

Minimax search with alpha-beta pruning, running live in the browser. Converted from Python.

AI Algorithms JavaScript

How it works

Minimax is a decision algorithm used in two-player games. The maximising player tries to maximise the score; the minimising player tries to minimise it. Alpha-beta pruning cuts branches that can't possibly affect the final decision, reducing the number of nodes evaluated.

function minimax(node, depth, alpha, beta, isMaximising) {
  if (depth === 0 || node.isLeaf) return node.value;

  if (isMaximising) {
    let best = -Infinity;
    for (const child of node.children) {
      best = Math.max(best, minimax(child, depth - 1, alpha, beta, false));
      alpha = Math.max(alpha, best);
      if (beta <= alpha) break; // prune
    }
    return best;
  } else {
    let best = Infinity;
    for (const child of node.children) {
      best = Math.min(best, minimax(child, depth - 1, alpha, beta, true));
      beta = Math.min(beta, best);
      if (beta <= alpha) break; // prune
    }
    return best;
  }
}