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