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