Fix types/initforms
[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$
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 (optimize (speed 3) (safety 0) (space 0)))
288   (setf (node-value node) (- (node-value node)))
289   node)
290
291 (defun legal-nodes (player board eval-fn)
292   "Return a list of legal moves, each one packed into a node."
293   (let ((moves (legal-moves player board)))
294     (sort (map-into
295             moves
296             #'(lambda (move)
297                 (let ((new-board (make-move move player
298                                             (copy-board board))))
299                   (make-node
300                     :square move :board new-board
301                     :value (funcall eval-fn player new-board))))
302             moves)
303           #'> :key #'node-value)))
304
305 (defun alpha-beta3 (player board achievable cutoff ply eval-fn
306                     killer)
307   (declare (type board board)
308            (type player player)
309            (type fixnum achievable cutoff ply)
310            (optimize (speed 3) (space 0) (safety 0)))
311   "A-B search, putting killer move first."
312   (if (= ply 0)
313       (funcall eval-fn player board)
314       (let ((moves (put-first killer (legal-moves player board))))
315         (if (null moves)
316             (if (any-legal-move? (opponent player) board)
317                 (- (alpha-beta3 (opponent player) board
318                                 (- cutoff) (- achievable)
319                                 (- ply 1) eval-fn nil))
320                 (final-value player board))
321             (let ((best-move (first moves))
322                   (new-board (svref *ply-boards* ply))
323                   (killer2 nil)
324                   (killer2-val winning-value))
325               (declare (type move best-move)
326                        (type board new-board)
327                        (type fixnum killer2-val))
328               (loop for move in moves
329                   do (multiple-value-bind (val reply)
330                        (alpha-beta3
331                         (opponent player)
332                         (make-move move player
333                                    (replace-board new-board board))
334                         (- cutoff) (- achievable)
335                         (- ply 1) eval-fn killer2)
336                        (setf val (- val))
337                        (when (> val achievable)
338                          (setq achievable val)
339                          (setq best-move move))
340                        (when (and reply (< val killer2-val))
341                          (setq killer2 reply)
342                          (setq killer2-val val)))
343                   until (>= achievable cutoff))
344               (values achievable best-move))))))
345
346 (defun alpha-beta3w (player board achievable cutoff ply eval-fn
347                     killer)
348   (declare (type board board)
349            (type player player)
350            (type fixnum achievable cutoff ply)
351            (type (or null move) killer)
352            (optimize (speed 3) (safety 0) (space 0)))
353   "A-B search, putting killer move first."
354   (if (= ply 0)
355       (funcall eval-fn player board)
356       (let ((moves (put-first killer (legal-moves player board))))
357         (if (null moves)
358             (if (any-legal-move? (opponent player) board)
359                 (- (alpha-beta3 (opponent player) board
360                                 (- cutoff) (- achievable)
361                                 (- ply 1) eval-fn nil))
362                 (final-value-weighted player board))
363             (let ((best-move (first moves))
364                   (new-board (svref *ply-boards* ply))
365                   (killer2 nil)
366                   (killer2-val winning-value))
367               (declare (type move best-move)
368                        (type board new-board)
369                        (type fixnum killer2-val))
370               (loop for move in moves
371                   do (multiple-value-bind (val reply)
372                        (alpha-beta3
373                         (opponent player)
374                         (make-move move player
375                                    (replace-board new-board board))
376                         (- cutoff) (- achievable)
377                         (- ply 1) eval-fn killer2)
378                        (setf val (- val))
379                        (when (> val achievable)
380                          (setq achievable val)
381                          (setq best-move move))
382                        (when (and reply (< val killer2-val))
383                          (setq killer2 reply)
384                          (setq killer2-val val)))
385                   until (>= achievable cutoff))
386               (values achievable best-move))))))
387
388
389 (defun alpha-beta-searcher3 (depth eval-fn)
390   "Return a strategy that does A-B search with killer moves."
391   #'(lambda (player board)
392       (declare (type board board)
393                (type player player))
394       (multiple-value-bind (value move)
395           (alpha-beta3 player board losing-value winning-value
396                        depth eval-fn nil)
397         (declare (ignore value))
398         move)))
399
400 (defun alpha-beta-searcher3w (depth eval-fn)
401   "Return a strategy that does A-B search with killer moves."
402   #'(lambda (player board)
403       (nth-value 1
404                  (alpha-beta3w player board losing-value winning-value
405                                depth eval-fn nil))))
406
407 (defun put-first (killer moves)
408   "Move the killer move to the front of moves,
409   if the killer move is in fact a legal move."
410   (if (member killer moves)
411       (cons killer (delete killer moves))
412       moves))
413
414 (defun mobility (player board)
415   "Current Mobility is the number of legal moves.
416   Potential mobility is the number of blank squares
417   adjacent to an opponent that are not legal moves.
418   Returns current and potential mobility for player."
419   (declare (type board board)
420            (type player player)
421            (optimize (speed 3) (safety 0) (space 0)))
422   (let ((opp (opponent player))
423         (current 0)    ; player's current mobility
424         (potential 0))                  ; player's potential mobility
425     (declare (type player opp)
426              (type fixnum current potential))
427     (dolist (square all-squares)
428       (declare (type square square))
429       (when (= (bref board square) empty)
430         (cond ((legal-p square player board)
431                (incf current))
432               ((some-neighbors board opp (neighbors square))
433                (incf potential))
434               )))
435     (values current (the fixnum (+ current potential)))))
436
437
438 (defun some-neighbors (board opp neighbors)
439   (declare (type board board)
440            (type player opp)
441            (type cons neighbors)
442            (optimize (speed 3) (safety 0) (space 0)))
443   (block search
444     (dolist (sq neighbors)
445       (declare (type square sq))
446       (when (= (bref board sq) opp)
447         (return-from search t)))
448     (return-from search nil)))
449
450 (defun edge-stability (player board)
451   "Total edge evaluation for player to move on board."
452   (declare (type board board)
453            (type player player)
454            (optimize (speed 3) (safety 0) (space 0)))
455   (loop for edge-list of-type (simple-array fixnum (*)) in *edge-and-x-lists*
456       sum (aref *edge-table* (edge-index player board edge-list))))
457
458 (defun iago-eval (player board)
459   "Combine edge-stability, current mobility and
460   potential mobility to arrive at an evaluation."
461   ;; The three factors are multiplied by coefficients
462   ;; that vary by move number:
463   (declare (type board board)
464            (type player player)
465            (optimize (speed 3) (safety 0) (space 0)))
466   (let ((c-edg  (+ 312000 (* 6240 *move-number*)))
467         (c-cur (if (< *move-number* 25)
468                    (+ 50000 (* 2000 *move-number*))
469                  (+ 75000 (* 1000 *move-number*))))
470         (c-pot 20000))
471     (declare (fixnum c-edg c-cur c-pot))
472     (multiple-value-bind (p-cur p-pot)
473         (mobility player board)
474       (multiple-value-bind (o-cur o-pot)
475           (mobility (opponent player) board)
476         ;; Combine the three factors into one sum:
477         (+ (round (* c-edg (edge-stability player board))
478                   32000)
479            (round (* c-cur (- p-cur o-cur))
480                   (+ p-cur o-cur 2))
481            (round (* c-pot (- p-pot o-pot))
482                   (+ p-pot o-pot 2)))))))
483
484
485 ;; Strategy Functions
486
487 (defun iago (depth)
488   "Use an approximation of Iago's evaluation function."
489   (declare (fixnum depth))
490   (alpha-beta-searcher3 depth #'iago-eval))
491
492 ;; Maximizer (1-ply)
493 (defun mx-df ()
494   (maximizer #'count-difference))
495
496 (defun mx-wt ()
497   (maximizer #'weighted-squares))
498
499 (defun mx-md-wt ()
500   (maximizer #'modified-weighted-squares))
501
502 ;; Minimax-searcher
503
504 (defun mm-df (ply)
505   (minimax-searcher ply #'count-difference))
506
507 (defun mm-wt (ply)
508   (minimax-searcher ply #'weighted-squares))
509
510 (defun mm-md-wt (ply)
511   (minimax-searcher ply #'modified-weighted-squares))
512
513 ;; Alpha-beta3 searcher
514 (defun ab3-df (ply)
515   (alpha-beta-searcher3 ply #'count-difference))
516
517 (defun ab3-wt (ply)
518   (alpha-beta-searcher3 ply #'weighted-squares))
519
520 (defun ab3-md-wt (ply)
521   (alpha-beta-searcher3 ply #'modified-weighted-squares))
522
523
524 (defun ab3w-df (ply)
525   (declare (fixnum ply))
526   (alpha-beta-searcher3w ply #'count-difference))
527
528 (defun ab3w-wt (ply)
529   (declare (fixnum ply))
530   (alpha-beta-searcher3w ply #'weighted-squares))
531
532 (defun ab3w-md-wt (ply)
533   (declare (fixnum 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