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