r3219: *** empty log message ***
[reversi.git] / base.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: reversi -*-
2 ;;;;***************************************************************************
3 ;;;;
4 ;;;; FILE IDENTIFICATION
5 ;;;; 
6 ;;;;  Name:           base.lisp
7 ;;;;  Purpose:        Basic functions for reversi
8 ;;;;  Programer:      Kevin Rosenberg based on code by Peter Norvig
9 ;;;;  Date Started:   1 Nov 2001
10 ;;;;
11 ;;;; $Id: base.lisp,v 1.2 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
25 (defparameter +all-directions+ '(-11 -10 -9 -1 1 9 10 11))
26 (defconstant +default-max-minutes+ 30)
27
28 (defconstant empty 0 "An empty square")
29 (defconstant black 1 "A black piece")
30 (defconstant white 2 "A white piece")
31 (defconstant outer 3 "Marks squares outside the 8x8 board")
32 ;;(declaim (type (unsigned-byte 8) empty black white outer))
33 (declaim (type fixnum empty black white outer))
34
35 #|
36 (deftype piece () '(unsigned-byte 8))
37 (deftype player () '(unsigned-byte 8))
38 (deftype move () '(unsigned-byte 8))
39 (deftype square () '(unsigned-byte 8))
40 |#
41
42 (deftype piece () 'fixnum)
43 (deftype player () 'fixnum)
44 (deftype move () 'fixnum)
45 (deftype square () 'fixnum)
46 (deftype dir () 'fixnum)
47 (deftype board () '(simple-array fixnum (100)))
48 ;;(deftype board () '(simple-array (unsigned-byte 8) (100)))
49 (deftype clock () '(simple-array integer (3)))
50
51 (defun make-moves ()
52   (make-array 60 :element-type 'cons :fill-pointer 0
53               :adjustable nil))
54 (deftype moves () '(array cons (60)))
55
56
57 (defclass reversi-game ()
58   ((bl-strategy :initarg :bl-strategy
59                 :documentation "Strategy function for black"
60                 :reader bl-strategy)
61    (wh-strategy :initarg :wh-strategy
62                 :documentation "Strategy function for white"
63                 :reader wh-strategy)
64    (board :type board :initarg :board
65           :documentation "The board configuration"
66           :reader board)
67    (move-number :type fixnum :initarg :move-number 
68                 :documentation "The number of the move to be played"
69                 :accessor move-number)
70    (player :type player :initarg :player
71                 :documentation "ID of next player to move"
72                 :accessor player)
73    (moves :type moves :initarg :moves
74           :documentation "An array of moves played in the game"
75           :accessor moves)
76    (print? :type boolean :initarg :print?
77            :documentation "Whether to print progress of this game"
78            :reader print?)
79    (record-game? :type boolean :initarg :record-game?
80            :documentation "Whether to record moves and clcck of this game"
81            :reader record-game?)
82    (final-result :type fixnum :initarg :final-result
83                  :documentation "Final count, is NIL while game in play"
84                  :accessor final-result)
85    (max-minutes :type fixnum :initarg :max-minutes
86                 :documentation "Maximum minites for each player"
87                 :reader max-minutes)
88    (clock :type clock :initarg :clock :initform nil
89           :documentation "An array of time-units left"
90           :accessor clock))
91   (:default-initargs 
92       :bl-strategy nil
93     :wh-strategy nil
94     :board (initial-board)
95     :move-number 1
96     :player black
97     :moves (make-moves)
98     :print? nil
99     :record-game? nil
100     :final-result nil
101     :max-minutes +default-max-minutes+
102     :clock (make-clock +default-max-minutes+)))
103
104
105 (defun name-of (piece) (char ".@O?" piece))
106 (defun title-of (piece) (nth (1- piece) '("Black" "White")) )
107        
108 (defmacro opponent (player) 
109   `(if (= ,player black) white black))
110
111 (defmacro bref (board square)
112   `(the piece (aref (the board ,board) (the square ,square))))
113
114 (defparameter all-squares
115     (loop for i from 11 to 88 when (<= 1 (mod i 10) 8) collect i)
116   "A list of all squares")
117
118 (defun initial-board ()
119   "Return a board, empty except for four pieces in the middle."
120   ;; Boards are 100-element vectors, with elements 11-88 used,
121   ;; and the others marked with the sentinel OUTER.  Initially
122   ;; the 4 center squares are taken, the others empty.
123   (let ((board (make-array 100 :element-type 'fixnum
124                            :initial-element outer
125                            :adjustable nil :fill-pointer nil)))
126     (declare (type board board))
127     (dolist (square all-squares)
128       (declare (fixnum square))
129       (setf (bref board square) empty))
130     (setf (bref board 44) white   (bref board 45) black
131           (bref board 54) black   (bref board 55) white)
132     board))
133
134 (defun copy-board (board)
135   (copy-seq board))
136
137 (defgeneric make-clock (clock))
138 (defmethod make-clock ((clock array))
139   (make-array (+ 1 (max black white))
140               :element-type 'integer
141               :initial-contents clock
142               :adjustable nil
143               :fill-pointer nil))
144
145 (defmethod make-clock ((minutes integer))
146   (make-array (+ 1 (max black white))
147               :element-type 'integer
148               :initial-element 
149               (* minutes 60 
150                  internal-time-units-per-second)
151               :adjustable nil
152               :fill-pointer nil))
153
154 (defun count-difference (player board)
155   "Count player's pieces minus opponent's pieces."
156   (declare (type board board)
157            (fixnum player))
158   (- (count player board)
159      (count (opponent player) board)))
160
161 (defun valid-p (move)
162   (declare (type move move))
163   "Valid moves are numbers in the range 11-88 that end in 1-8."
164   (and (typep move 'move) (<= 11 move 88) (<= 1 (mod move 10) 8)))
165
166 #+ignore
167 (defun legal-p (move player board)
168   "A Legal move must be into an empty square, and it must
169   flip at least one opponent piece."
170   (declare (type board board)
171            (type move move)
172            (type player player))
173   (and (= (the piece (bref board move)) empty)
174        (some #'(lambda (dir) (declare (type dir dir)) (would-flip? move player board dir))
175              +all-directions+)))
176
177 #+ignore
178 (defun legal-p (move player board)
179   "A Legal move must be into an empty square, and it must
180   flip at least one opponent piece."
181   (declare (type board board)
182            (type move move)
183            (type player player)
184            (optimize speed (safety 0))
185 )
186   (if (= (bref board move) empty)
187       (block search
188         (let ((i 0))
189           (declare (fixnum i))
190           (tagbody t
191             (when (>= i 8) (return-from search nil))
192             (when (would-flip? move player board (aref +all-directions+ i))
193               (return-from search t))
194             (incf i)
195             (go t))))
196     nil))
197
198 (defun legal-p (move player board)
199   "A Legal move must be into an empty square, and it must
200   flip at least one opponent piece."
201   (declare (type board board)
202            (type move move)
203            (type player player)
204            (optimize (speed 3) (safety 0))
205 )
206   (if (= (the piece (bref board move)) empty)
207       (block search
208         (dolist (dir +all-directions+)
209           (declare (type dir dir))
210           (when (would-flip? move player board dir)
211             (return-from search t)))
212         (return-from search nil))
213     nil))
214
215 (defstruct (state (:constructor make-state-struct))
216   move player board clock)
217
218 (defun make-state (move player clock board)
219   (make-state-struct :move move :player player :clock (make-clock clock) :board (copy-board board)))
220
221 (defun make-game-move (game move player)
222   (when (record-game? game)
223     (vector-push (make-state move player (clock game) (board game))
224                  (moves game)))
225   (make-move move player (board game))
226   (incf (move-number game)))
227
228 (defun reset-game (game &optional (move-number 1))
229   (if (record-game? game)
230       (when (< move-number (move-number game))
231         (let ((old-state (aref (moves game) (1- move-number))))
232           (if old-state
233               (progn
234                 (setf (player game) (state-player old-state))
235                 (replace-board (board game) (state-board old-state))
236                 (replace (clock game) (state-clock old-state))
237                 (setf (fill-pointer (moves game)) (1- move-number))
238                 (setf (move-number game) move-number))
239             (warn "Couldn't find old state"))))
240   (warn "Tried to reset game, but game is not being recorded")))
241   
242 (defun make-move (move player board)
243   "Update board to reflect move by player"
244   ;; First make the move, then make any flips
245   (declare (type board board)
246            (type move move)
247            (type player)
248            (optimize (speed 3) (safety 0))
249 )
250   (setf (bref board move) player)
251   (dolist (dir +all-directions+)
252     (declare (type dir dir))
253     (make-flips move player board dir))
254   board)
255
256 (defun make-flips (move player board dir)
257   "Make any flips in the given direction."
258   (declare (type board board)
259            (type move move)
260            (type player player)
261            (type dir dir)
262            (optimize (speed 3) (safety 0))
263 )
264   (let ((bracketer (would-flip? move player board dir)))
265     (when bracketer
266       (loop for c from (+ move dir) by dir until (= c (the fixnum bracketer))
267             do (setf (bref board c) player)))))
268
269 (defun would-flip? (move player board dir)
270   "Would this move result in any flips in this direction?
271   If so, return the square number of the bracketing piece."
272   ;; A flip occurs if, starting at the adjacent square, c, there
273   ;; is a string of at least one opponent pieces, bracketed by 
274   ;; one of player's pieces
275   (declare (type board board)
276            (type move move)
277            (type player player)
278            (type dir dir)
279            (optimize (speed 3) (safety 0))
280 )
281   (let ((c (+ move dir)))
282     (declare (type square c))
283     (and (= (the piece (bref board c)) (the player (opponent player)))
284          (find-bracketing-piece (+ c dir) player board dir))))
285
286 (defun find-bracketing-piece (square player board dir)
287   "Return the square number of the bracketing piece."
288   (declare (type board board)
289            (type square square)
290            (type player player)
291            (type dir dir)
292            (optimize (speed 3) (safety 0))
293 )
294   (cond ((= (bref board square) player) square)
295         ((= (bref board square) (the player (opponent player)))
296          (find-bracketing-piece (the square (+ square dir)) player board dir))
297         (t nil)))
298
299 (defun next-to-play (board previous-player &optional (print nil))
300   "Compute the player to move next, or NIL if nobody can move."
301   (declare (type board board)
302            (type player previous-player)
303            (type boolean print))
304   (let ((opp (opponent previous-player)))
305     (cond ((any-legal-move? opp board) opp)
306           ((any-legal-move? previous-player board) 
307            (when print
308              (format t "~&~c has no moves and must pass."
309                      (name-of opp)))
310            previous-player)
311           (t nil))))
312
313 (defun any-legal-move? (player board)
314   "Does player have any legal moves in this position?"
315   (declare (type player player)
316            (type board board))
317   (some #'(lambda (move) (declare (type move move)) (legal-p move player board))
318         all-squares))
319
320
321 (defun legal-moves (player board)
322   "Returns a list of legal moves for player"
323   ;;*** fix, segre, 3/30/93.  Was remove-if, which can share with all-squares.
324   (declare (type player player)
325            (type board board))
326   (loop for move in all-squares
327       when (legal-p move player board) collect move))
328
329 #-allegro
330 (defun replace-board (to from)
331   (replace to from))
332
333 #+ignore
334 (defun replace-board (to from)
335   (declare (type board to from)
336            (optimize (safety 0) (debug 0) (speed 3))
337 )
338   (dotimes (i 100)
339     (declare (type 'fixnum i))
340     (setf (aref to i) (aref from i)))
341   to)
342
343 #+allegro
344 (defun replace-board (to from)
345   (declare (type board to from))
346   (ff::fslot-memory-copy to 0 400 from)
347   to)
348
349 (defvar *ply-boards*
350   (apply #'vector (loop repeat 40 collect (initial-board))))
351
352
353
354 (defvar *move-number* 1 "The number of the move to be played")
355 (declaim (type fixnum *move-number*))
356
357 (defun make-game (bl-strategy wh-strategy 
358                   &key 
359                   (print t) 
360                   (minutes +default-max-minutes+)
361                   (record-game nil))
362   (let ((game
363          (make-instance 'reversi-game :bl-strategy bl-strategy
364                         :wh-strategy wh-strategy
365                         :print? print
366                         :record-game? record-game
367                         :max-minutes minutes)))
368     (setf (clock game) (make-clock minutes))
369     game))
370
371 (defun play-game (game)
372   (catch 'game-over
373     (until (null (player game))
374            (setq *move-number* (move-number game))
375            (get-move game
376                      (if (= (player game) black) 
377                          (bl-strategy game)
378                        (wh-strategy game))
379                      (player game)
380                      (board game) (print? game) (clock game))
381            (setf (player game) 
382              (next-to-play (board game) (player game) (print? game)))
383            (incf (move-number game))))
384   (when (print? game)
385     (format t "~&The game is over.  Final result:")
386     (print-board (board game) (clock game)))
387   (count-difference black (board game)))
388
389
390 (defun reversi (bl-strategy wh-strategy 
391                 &optional (print t) (minutes +default-max-minutes+))
392   (play-game (make-game bl-strategy wh-strategy :print print
393                         :record-game nil :minutes minutes)))
394
395 (defvar *clock* (make-clock +default-max-minutes+) "A copy of the game clock")
396 (defvar *board* (initial-board) "A copy of the game board")
397
398 (defun get-move (game strategy player board print clock)
399   "Call the player's strategy function to get a move.
400   Keep calling until a legal move is made."
401   ;; Note we don't pass the strategy function the REAL board.
402   ;; If we did, it could cheat by changing the pieces on the board.
403   (when print (print-board board clock))
404   (replace *clock* clock)
405   (let* ((t0 (get-internal-real-time))
406          (move (funcall strategy player (replace-board *board* board)))
407          (t1 (get-internal-real-time)))
408     (decf (elt clock player) (- t1 t0))
409     (cond
410       ((< (elt clock player) 0)
411        (format t "~&~c has no time left and forfeits."
412                (name-of player))
413        (throw 'game-over (if (eql player black) -64 64)))
414       ((eq move 'resign)
415        (throw 'game-over (if (eql player black) -64 64)))
416       ((and (valid-p move) (legal-p move player board))
417        (when print
418          (format t "~&~c moves to ~a." 
419                  (name-of player) (88->h8 move)))
420        (make-game-move game move player))
421       (t (warn "Illegal move: ~a" (88->h8 move))
422          (get-move game strategy player board print clock)))))
423
424
425 (defun random-reversi-series (strategy1 strategy2 
426                               n-pairs &optional (n-random 10))
427   "Play a series of 2*n games, starting from a random position."
428   (reversi-series
429     (switch-strategies #'random-strategy n-random strategy1)
430     (switch-strategies #'random-strategy n-random strategy2)
431     n-pairs))
432
433 (defun switch-strategies (strategy1 m strategy2)
434   "Make a new strategy that plays strategy1 for m moves,
435   then plays according to strategy2."
436   #'(lambda (player board)
437       (funcall (if (<= *move-number* m) strategy1 strategy2)
438                player board)))
439
440 (defun reversi-series (strategy1 strategy2 n-pairs)
441   "Play a series of 2*n-pairs games, swapping sides."
442   (let ((scores
443           (loop repeat n-pairs
444              for random-state = (make-random-state)
445              collect (reversi strategy1 strategy2 nil)
446              do (setf *random-state* random-state)
447              collect (- (reversi strategy2 strategy1 nil)))))
448     ;; Return the number of wins (1/2 for a tie),
449     ;; the total of the point differences, and the
450     ;; scores themselves, all from strategy1's point of view.
451     (values (+ (count-if #'plusp scores)
452                (/ (count-if #'zerop scores) 2))
453             (apply #'+ scores)
454             scores)))
455
456 (defun round-robin (strategies n-pairs &optional
457                     (n-random 10) (names strategies))
458   "Play a tournament among the strategies.
459   N-PAIRS = games each strategy plays as each color against
460   each opponent.  So with N strategies, a total of
461   N*(N-1)*N-PAIRS games are played."
462   (let* ((N (length strategies))
463          (totals (make-array N :initial-element 0))
464          (scores (make-array (list N N)
465                              :initial-element 0)))
466     ;; Play the games
467     (dotimes (i N)
468       (loop for j from (+ i 1) to (- N 1) do 
469           (let* ((wins (random-reversi-series
470                          (elt strategies i)
471                          (elt strategies j)
472                          n-pairs n-random))
473                  (losses (- (* 2 n-pairs) wins)))
474             (incf (aref scores i j) wins)
475             (incf (aref scores j i) losses)
476             (incf (aref totals i) wins)
477             (incf (aref totals j) losses))))
478     ;; Print the results
479     (dotimes (i N)
480       (format t "~&~a~20T ~4f: " (elt names i) (elt totals i))
481       (dotimes (j N)
482         (format t "~4f " (if (eql i j) '---
483                            (aref scores i j)))))))
484