;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/id-alpha-beta.lisp

;;;; Iterative Deepening Alpha-Beta Search

;;; A two-player alpha-beta search with a depth cutoff, written from the
;;; point of view of the player to move at the root, and the iterative
;;; deepening loop of [Section 5.3.2] around it, which searches to depth
;;; 1, 2, 3, ... and keeps the move of the deepest completed search, so
;;; that a move is always ready when the time runs out.  EVAL-FN takes a
;;; state and returns the list of its values for the players, in the order
;;; of GAME-STATE-PLAYERS (as TTT-EVAL does).

(defun alpha-beta-cutoff-decision (state game eval-fn &optional (depth 4))
  "Return the best move for the player to move in STATE, searching DEPTH
  plies and then applying EVAL-FN. [Fig. 5.7, with a cutoff]"
  (let ((player (current-player state))
	(alpha minus-infinity)
	(best-move nil))
    (dolist (move (legal-moves game state) best-move)
      (let ((v (alpha-beta-cutoff-value (make-move game state move) game
					player alpha infinity
					eval-fn (- depth 1))))
	(when (or (null best-move) (> v alpha))
	  (setf alpha v
		best-move move))))))

(defun alpha-beta-cutoff-value (state game player alpha beta eval-fn depth)
  "The alpha-beta value of STATE for PLAYER, searching DEPTH more plies."
  (cond ((game-over? game state)
	 (getf (game-state-scores state) player 0))
	((<= depth 0)
	 (elt (funcall eval-fn state)
	      (position player (game-state-players state))))
	((eq (current-player state) player)
	 (let ((v minus-infinity))
	   (dolist (move (legal-moves game state) v)
	     (setf v (max v (alpha-beta-cutoff-value
			     (make-move game state move) game player
			     alpha beta eval-fn (- depth 1))))
	     (when (>= v beta) (return v))
	     (setf alpha (max alpha v)))))
	(t
	 (let ((v infinity))
	   (dolist (move (legal-moves game state) v)
	     (setf v (min v (alpha-beta-cutoff-value
			     (make-move game state move) game player
			     alpha beta eval-fn (- depth 1))))
	     (when (<= v alpha) (return v))
	     (setf beta (min beta v)))))))

(defun iterative-deepening-alpha-beta-decision (state game eval-fn
						&key (time-limit 1.0)
						     (max-depth 9))
  "Run ALPHA-BETA-CUTOFF-DECISION with depths 1, 2, ..., MAX-DEPTH, until
  TIME-LIMIT seconds have passed; return the move of the deepest search.
  [Section 5.3.2]"
  (let ((start (get-internal-real-time))
	(move nil))
    (loop for depth from 1 to max-depth do
	  (setf move (alpha-beta-cutoff-decision state game eval-fn depth))
	  (when (> (/ (- (get-internal-real-time) start)
		      internal-time-units-per-second)
		   time-limit)
	    (return)))
    move))
