r4846: Auto commit for Debian build
[reversi.git] / strategies.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: reversi -*-
2 ;;;;***************************************************************************
3 ;;;;
4 ;;;; FILE IDENTIFICATION
5 ;;;; 
6 ;;;;  Name:           strategies.lisp
7 ;;;;  Purpose:        Strategy routines for reversi
8 ;;;;  Programer:      Kevin Rosenberg based on code by Peter Norvig
9 ;;;;  Date Started:   1 Nov 2001
10 ;;;;
11 ;;;; $Id: strategies.lisp,v 1.5 2003/05/06 15:51:20 kevin Exp $
12 ;;;;
13 ;;;; This file is Copyright (c) 2001-2002 by Kevin M. Rosenberg 
14 ;;;; and Copyright (c) 1998-2002 Peter Norvig
15 ;;;;
16 ;;;; Reversi users are granted the rights to distribute and use this software
17 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
18 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
19 ;;;;***************************************************************************
20
21 (in-package #:reversi)
22
23 (eval-when (:compile-toplevel)
24   (declaim (optimize (safety 1) (space 0) (speed 3) (compilation-speed 0))))
25
26 (defun random-strategy (player board)
27   "Make any legal move."
28   (declare (type player player)
29            (type board board))
30   (random-elt (legal-moves player board)))
31
32
33 (defun maximize-difference (player board)
34   "A strategy that maximizes the difference in pieces."
35   (declare (type player player)
36            (type board board))
37   (funcall (maximizer #'count-difference) player board))
38
39 (defun maximizer (eval-fn)
40   "Return a strategy that will consider every legal move,
41   apply EVAL-FN to each resulting board, and choose 
42   the move for which EVAL-FN returns the best score.
43   FN takes two arguments: the player-to-move and board"
44   #'(lambda (player board)
45       (declare (type player player)
46                (type board board))
47       (let* ((moves (legal-moves player board))
48              (scores (mapcar #'(lambda (move)
49                                  (funcall
50                                   eval-fn
51                                   player
52                                   (make-move move player
53                                              (copy-board board))))
54                              moves))
55              (best (apply #'max scores)))
56         (declare (fixnum best))
57         (elt moves (position best scores)))))
58
59 (eval-when (:compile-toplevel :load-toplevel :execute)
60   (defparameter *weights*
61       (make-array 100 :element-type 'fixnum 
62                   :fill-pointer nil :adjustable nil
63                   :initial-contents
64                   '(0   0   0  0  0  0  0   0  0 0
65                     0 120 -20 20  5  5 20 -20 120 0
66                     0 -20 -40 -5 -5 -5 -5 -40 -20 0
67                     0  20  -5 15  3  3 15  -5  20 0
68                     0   5  -5  3  3  3  3  -5   5 0
69                     0   5  -5  3  3  3  3  -5   5 0
70                     0  20  -5 15  3  3 15  -5  20 0
71                     0 -20 -40 -5 -5 -5 -5 -40 -20 0
72                     0 120 -20 20  5  5 20 -20 120 0
73                     0   0   0  0  0  0  0   0   0 0)))
74   (declaim (type (simple-array fixnum (100)) *weights*))
75 )
76
77 (eval-when (:compile-toplevel :load-toplevel :execute)
78   (setq all-squares 
79     (sort (loop for i from 11 to 88 
80               when (<= 1 (mod i 10) 8) collect i)
81           #'> :key #'(lambda (sq) (elt *weights* sq)))))
82
83
84 (defun weighted-squares (player board)
85   "Sum of the weights of player's squares minus opponent's."
86   (declare (type player player)
87            (type board board))
88   (let ((opp (opponent player)))
89     (loop for i in all-squares
90           when (= (bref board i) player) 
91           sum (aref *weights* i)
92           when (= (bref board i) opp)
93           sum (- (aref *weights* i)))))
94
95 (defconstant winning-value (- most-positive-fixnum 70))
96 (defconstant losing-value  (+ most-negative-fixnum 70))
97
98 (defun final-value (player board)
99   "Is this a win, loss, or draw for player?"
100   (declare (type player player)
101            (type board board))
102   (case (signum (count-difference player board))
103     (-1 losing-value)
104     ( 0 0)
105     (+1 winning-value)))
106
107 (defun final-value-weighted (player board)
108   "Is this a win, loss, or draw for player?"
109   (declare (type player player)
110            (type board board))
111   (let ((diff (count-difference player board)))
112     (case (signum diff)
113       (-1 (+ losing-value diff))
114       ( 0 0)
115       (+1 (+ winning-value diff)))))
116
117 (defun minimax (player board ply eval-fn)
118   "Find the best move, for PLAYER, according to EVAL-FN,
119   searching PLY levels deep and backing up values."
120   (declare (type player player)
121            (type board board)
122            (fixnum ply))
123   (if (= ply 0)
124       (funcall eval-fn player board)
125       (let ((moves (legal-moves player board)))
126         (if (null moves)
127             (if (any-legal-move? (opponent player) board)
128                 (- (minimax (opponent player) board
129                             (- ply 1) eval-fn))
130                 (final-value player board))
131             (let ((best-move nil)
132                   (best-val nil))
133               (dolist (move moves)
134                 (let* ((board2 (make-move move player
135                                           (copy-board board)))
136                        (val (- (minimax
137                                  (opponent player) board2
138                                  (- ply 1) eval-fn))))
139                   (when (or (null best-val)
140                             (> val best-val))
141                     (setf best-val val)
142                     (setf best-move move))))
143               (values best-val best-move))))))
144
145 (defun minimax-searcher (ply eval-fn)
146   "A strategy that searches PLY levels and then uses EVAL-FN."
147   #'(lambda (player board)
148       (declare (type player player)
149                (type board board))
150       (multiple-value-bind (value move)
151           (minimax player board ply eval-fn) 
152         (declare (ignore value))
153         move)))
154
155 (defun alpha-beta (player board achievable cutoff ply eval-fn)
156   "Find the best move, for PLAYER, according to EVAL-FN,
157   searching PLY levels deep and backing up values,
158   using cutoffs whenever possible."
159   (declare (type player player)
160            (type board board)
161            (fixnum achievable cutoff ply))
162   (if (= ply 0)
163       (funcall eval-fn player board)
164       (let ((moves (legal-moves player board)))
165         (if (null moves)
166             (if (any-legal-move? (opponent player) board)
167                 (- (alpha-beta (opponent player) board
168                                (- cutoff) (- achievable)
169                                (- ply 1) eval-fn))
170                 (final-value player board))
171           (let ((best-move (first moves)))
172             (declare (type move best-move))
173             (loop for move in moves do
174                   (let* ((board2 (make-move move player
175                                             (copy-board board)))
176                          (val (- (alpha-beta
177                                  (opponent player) board2
178                                  (- cutoff) (- achievable)
179                                  (- ply 1) eval-fn))))
180                   (when (> val achievable)
181                     (setf achievable val)
182                     (setf best-move move)))
183                 until (>= achievable cutoff))
184               (values achievable best-move))))))
185
186 (defun alpha-beta-searcher (depth eval-fn)
187   "A strategy that searches to DEPTH and then uses EVAL-FN."
188   (declare (fixnum depth))
189   #'(lambda (player board)
190       (declare (type board board)
191                (type player player))
192       (multiple-value-bind (value move)
193           (alpha-beta player board losing-value winning-value
194                       depth eval-fn) 
195         (declare (ignore value))
196         move)))
197
198 (defun modified-weighted-squares (player board)
199   "Like WEIGHTED-SQUARES, but don't take off for moving
200   near an occupied corner."
201   (declare (type player player)
202            (type board board))
203   (let ((w (weighted-squares player board)))
204     (declare (fixnum w))
205     (dolist (corner '(11 18 81 88))
206       (declare (type square corner))
207       (when (not (= (bref board corner) empty))
208         (dolist (c (neighbors corner))
209           (declare (type square c))
210           (when (not (= (bref board c) empty))
211             (incf w (* (- 5 (aref *weights* c))
212                        (if (= (bref board c) player)
213                            +1 -1)))))))
214     w))
215
216 (eval-when (:compile-toplevel :load-toplevel :execute)
217 (let ((neighbor-table (make-array 100 :initial-element nil)))
218   ;; Initialize the neighbor table
219   (dolist (square all-squares)
220     (declare (type square square))
221     (dolist (dir +all-directions+)
222       (declare (type dir dir))
223       (if (valid-p (+ square dir))
224           (push (+ square dir)
225                 (aref neighbor-table square)))))
226
227   (defun neighbors (square)
228     "Return a list of all squares adjacent to a square."
229     (aref neighbor-table square))))
230
231
232 (defun mobility-simple (player board)
233   "The number of moves a player has."
234   (length (legal-moves player board)))
235
236
237
238 (defstruct (node) 
239   (square(missing-argument) :type square)
240   (board (missing-argument) :type board)
241   (value (missing-argument) :type integer))
242
243 (defun alpha-beta-searcher2 (depth eval-fn)
244   "Return a strategy that does A-B search with sorted moves."
245   #'(lambda (player board)
246       (declare (type player player)
247                (type board board))
248       (multiple-value-bind (value node)
249           (alpha-beta2
250             player (make-node :board board
251                               :value (funcall eval-fn player board))
252             losing-value winning-value depth eval-fn)
253         (declare (ignore value))
254         (node-square node))))
255
256 (defun alpha-beta2 (player node achievable cutoff ply eval-fn)
257   "A-B search, sorting moves by eval-fn"
258   ;; Returns two values: achievable-value and move-to-make
259   (if (= ply 0)
260       (values (node-value node) node)
261       (let* ((board (node-board node))
262              (nodes (legal-nodes player board eval-fn)))
263         (if (null nodes)
264             (if (any-legal-move? (opponent player) board)
265                 (values (- (alpha-beta2 (opponent player)
266                                         (negate-value node)
267                                         (- cutoff) (- achievable)
268                                         (- ply 1) eval-fn))
269                         nil)
270                 (values (final-value player board) nil))
271           (let ((best-node (first nodes)))
272               (loop for move in nodes
273                     for val = (- (alpha-beta2
274                                    (opponent player)
275                                    (negate-value move)
276                                    (- cutoff) (- achievable)
277                                    (- ply 1) eval-fn))
278                     do (when (> val achievable)
279                          (setf achievable val)
280                          (setf best-node move))
281                     until (>= achievable cutoff))
282               (values achievable best-node))))))
283
284 (defun negate-value (node)
285   "Set the value of a node to its negative."
286   (setf (node-value node) (- (node-value node)))
287   node)
288
289 (defun legal-nodes (player board eval-fn)
290   "Return a list of legal moves, each one packed into a node."
291   (let ((moves (legal-moves player board)))
292     (sort (map-into
293             moves
294             #'(lambda (move)
295                 (let ((new-board (make-move move player
296                                             (copy-board board))))
297                   (make-node
298                     :square move :board new-board
299                     :value (funcall eval-fn player new-board))))
300             moves)
301           #'> :key #'node-value)))
302
303 (defun alpha-beta3 (player board achievable cutoff ply eval-fn
304                     killer)
305   (declare (type board board)
306            (type player player)
307            (type fixnum achievable cutoff ply))
308   "A-B search, putting killer move first."
309   (if (= ply 0)
310       (funcall eval-fn player board)
311       (let ((moves (put-first killer (legal-moves player board))))
312         (if (null moves)
313             (if (any-legal-move? (opponent player) board)
314                 (- (alpha-beta3 (opponent player) board
315                                 (- cutoff) (- achievable)
316                                 (- ply 1) eval-fn nil))
317                 (final-value player board))
318             (let ((best-move (first moves))
319                   (new-board (svref *ply-boards* ply))
320                   (killer2 nil)
321                   (killer2-val winning-value))
322               (declare (type move best-move)
323                        (type board new-board)
324                        (type fixnum killer2-val))
325               (loop for move in moves
326                   do (multiple-value-bind (val reply)
327                        (alpha-beta3
328                         (opponent player)
329                         (make-move move player
330                                    (replace-board new-board board))
331                         (- cutoff) (- achievable)
332                         (- ply 1) eval-fn killer2)
333                        (setf val (- val))
334                        (when (> val achievable)
335                          (setq achievable val)
336                          (setq best-move move))
337                        (when (and reply (< val killer2-val))
338                          (setq killer2 reply)
339                          (setq killer2-val val)))
340                   until (>= achievable cutoff))
341               (values achievable best-move))))))
342
343 (defun alpha-beta3w (player board achievable cutoff ply eval-fn
344                     killer)
345   (declare (type board board)
346            (type player player)
347            (type fixnum achievable cutoff ply)
348            (type move killer))
349   "A-B search, putting killer move first."
350   (if (= ply 0)
351       (funcall eval-fn player board)
352       (let ((moves (put-first killer (legal-moves player board))))
353         (if (null moves)
354             (if (any-legal-move? (opponent player) board)
355                 (- (alpha-beta3 (opponent player) board
356                                 (- cutoff) (- achievable)
357                                 (- ply 1) eval-fn nil))
358                 (final-value-weighted player board))
359             (let ((best-move (first moves))
360                   (new-board (svref *ply-boards* ply))
361                   (killer2 nil)
362                   (killer2-val winning-value))
363               (declare (type move best-move)
364                        (type board new-board)
365                        (type fixnum killer2-val))
366               (loop for move in moves
367                   do (multiple-value-bind (val reply)
368                        (alpha-beta3
369                         (opponent player)
370                         (make-move move player
371                                    (replace-board new-board board))
372                         (- cutoff) (- achievable)
373                         (- ply 1) eval-fn killer2)
374                        (setf val (- val))
375                        (when (> val achievable)
376                          (setq achievable val)
377                          (setq best-move move))
378                        (when (and reply (< val killer2-val))
379                          (setq killer2 reply)
380                          (setq killer2-val val)))
381                   until (>= achievable cutoff))
382               (values achievable best-move))))))
383
384
385 (defun alpha-beta-searcher3 (depth eval-fn)
386   "Return a strategy that does A-B search with killer moves."
387   #'(lambda (player board)
388       (declare (type board board)
389                (type player player))
390       (multiple-value-bind (value move)
391           (alpha-beta3 player board losing-value winning-value
392                        depth eval-fn nil)
393         (declare (ignore value))
394         move)))
395
396 (defun alpha-beta-searcher3w (depth eval-fn)
397   "Return a strategy that does A-B search with killer moves."
398   #'(lambda (player board)
399       (multiple-value-bind (value move)
400           (alpha-beta3w player board losing-value winning-value
401                        depth eval-fn nil)
402         (declare (ignore value))
403         move)))
404
405 (defun put-first (killer moves)
406   "Move the killer move to the front of moves,
407   if the killer move is in fact a legal move."
408   (if (member killer moves)
409       (cons killer (delete killer moves))
410       moves))
411
412 (defun mobility (player board)
413   "Current Mobility is the number of legal moves.
414   Potential mobility is the number of blank squares
415   adjacent to an opponent that are not legal moves.
416   Returns current and potential mobility for player."
417   (declare (type board board)
418            (type player player)
419            (optimize (speed 3) (safety 0 )))
420   (let ((opp (opponent player))
421         (current 0)    ; player's current mobility
422         (potential 0))                  ; player's potential mobility
423     (declare (type player opp)
424              (type fixnum current potential))
425     (dolist (square all-squares)
426       (declare (type square square))
427       (when (= (bref board square) empty)
428         (cond ((legal-p square player board)
429                (incf current))
430               ((some-neighbors board opp (neighbors square))
431                (incf potential))
432               )))
433     (values current (the fixnum (+ current potential)))))
434
435
436 (defun some-neighbors (board opp neighbors)
437   (declare (type board board)
438            (type player opp)
439            (type cons neighbors)
440            (optimize (speed 3) (safety 0)))
441   (block search
442     (dolist (sq neighbors)
443       (declare (type square sq))
444       (when (= (bref board sq) opp)
445         (return-from search t)))
446     (return-from search nil)))
447
448 (defun edge-stability (player board)
449   "Total edge evaluation for player to move on board."
450   (declare (type board board)
451            (type player player))
452   (loop for edge-list in *edge-and-x-lists*
453         sum (aref *edge-table*
454                   (edge-index player board edge-list))))
455
456 (defun iago-eval (player board)
457   "Combine edge-stability, current mobility and
458   potential mobility to arrive at an evaluation."
459   ;; The three factors are multiplied by coefficients
460   ;; that vary by move number:
461   (declare (type board board)
462            (type player player))
463   (let ((c-edg  (+ 312000 (* 6240 *move-number*)))
464         (c-cur (if (< *move-number* 25)
465                    (+ 50000 (* 2000 *move-number*))
466                  (+ 75000 (* 1000 *move-number*))))
467         (c-pot 20000))
468     (declare (fixnum c-edg c-cur c-pot))
469     (multiple-value-bind (p-cur p-pot)
470         (mobility player board)
471       (multiple-value-bind (o-cur o-pot)
472           (mobility (opponent player) board)
473         ;; Combine the three factors into one sum:
474         (+ (round (* c-edg (edge-stability player board))
475                   32000)
476            (round (* c-cur (- p-cur o-cur))
477                   (+ p-cur o-cur 2))
478            (round (* c-pot (- p-pot o-pot))
479                   (+ p-pot o-pot 2)))))))
480
481
482 ;; Strategy Functions
483
484 (defun iago (depth)
485   "Use an approximation of Iago's evaluation function."
486   (alpha-beta-searcher3 depth #'iago-eval))
487
488 ;; Maximizer (1-ply)
489 (defun mx-df ()
490   (maximizer #'count-difference))
491
492 (defun mx-wt ()
493   (maximizer #'weighted-squares))
494
495 (defun mx-md-wt ()
496   (maximizer #'modified-weighted-squares))
497
498 ;; Minimax-searcher
499
500 (defun mm-df (ply)
501   (minimax-searcher ply #'count-difference))
502
503 (defun mm-wt (ply)
504   (minimax-searcher ply #'weighted-squares))
505
506 (defun mm-md-wt (ply)
507   (minimax-searcher ply #'modified-weighted-squares))
508
509 ;; Alpha-beta3 searcher
510 (defun ab3-df (ply)
511   (alpha-beta-searcher3 ply #'count-difference))
512
513 (defun ab3-wt (ply)
514   (alpha-beta-searcher3 ply #'weighted-squares))
515
516 (defun ab3-md-wt (ply)
517   (alpha-beta-searcher3 ply #'modified-weighted-squares))
518
519
520 (defun ab3w-df (ply)
521   (alpha-beta-searcher3w ply #'count-difference))
522
523 (defun ab3w-wt (ply)
524   (alpha-beta-searcher3w ply #'weighted-squares))
525
526 (defun ab3w-md-wt (ply)
527   (alpha-beta-searcher3w ply #'modified-weighted-squares))
528
529
530 (defun rr (ply n-pairs)
531   (round-robin 
532    (list #'random-strategy (ab3-df ply) (ab3-wt ply) (ab3-md-wt ply) (iago 3)) 
533    n-pairs 
534    10
535    '(random ab3-df ab3-wt ab3-md-wt iago)))
536
537   
538 (defun text-reversi ()
539   "Sets up a text game between player and computer"
540   )
541
542                                           
543