8a6dd146f494a4a3845eb448a9525893e73c2142
[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.6 2003/06/12 13:28:55 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) (space 0)))
189   (if (= (bref board move) empty)
190       (block search
191         (let ((i 0))
192           (declare (fixnum i))
193           (tagbody t
194             (when (>= i 8) (return-from search nil))
195             (when (would-flip? move player board (aref +all-directions+ i))
196               (return-from search t))
197             (incf i)
198             (go t))))
199     nil))
200
201 (defun legal-p (move player board)
202   "A Legal move must be into an empty square, and it must
203   flip at least one opponent piece."
204   (declare (type board board)
205            (type move move)
206            (type player player)
207            (optimize (speed 3) (safety 0) (space 0)))
208   (if (= (the piece (bref board move)) empty)
209       (block search
210         (dolist (dir +all-directions+)
211           (declare (type dir dir))
212           (when (would-flip? move player board dir)
213             (return-from search t)))
214         (return-from search nil))
215     nil))
216
217 (defstruct (state (:constructor make-state-struct))
218   move player board clock)
219
220 (defun make-state (move player clock board)
221   (make-state-struct :move move :player player :clock (make-clock clock) :board (copy-board board)))
222
223 (defun make-game-move (game move player)
224   (when (record-game? game)
225     (vector-push (make-state move player (clock game) (board game))
226                  (moves game)))
227   (make-move move player (board game))
228   (incf (move-number game)))
229
230 (defun reset-game (game &optional (move-number 1))
231   (if (record-game? game)
232       (when (< move-number (move-number game))
233         (let ((old-state (aref (moves game) (1- move-number))))
234           (if old-state
235               (progn
236                 (setf (player game) (state-player old-state))
237                 (replace-board (board game) (state-board old-state))
238                 (replace (clock game) (state-clock old-state))
239                 (setf (fill-pointer (moves game)) (1- move-number))
240                 (setf (move-number game) move-number))
241             (warn "Couldn't find old state"))))
242   (warn "Tried to reset game, but game is not being recorded")))
243   
244 (defun make-move (move player board)
245   "Update board to reflect move by player"
246   ;; First make the move, then make any flips
247   (declare (type board board)
248            (type move move)
249            (type player)
250            (optimize (speed 3) (safety 0) (space 0)))
251   (setf (bref board move) player)
252   (dolist (dir +all-directions+)
253     (declare (type dir dir))
254     (make-flips move player board dir))
255   board)
256
257 (defun make-flips (move player board dir)
258   "Make any flips in the given direction."
259   (declare (type board board)
260            (type move move)
261            (type player player)
262            (type dir dir)
263            (optimize (speed 3) (safety 0) (space 0)))
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) (space 0)))
280   (let ((c (+ move dir)))
281     (declare (type square c))
282     (and (= (the piece (bref board c)) (the player (opponent player)))
283          (find-bracketing-piece (the fixnum (+ c dir)) player board dir))))
284
285 (defun find-bracketing-piece (square player board dir)
286   "Return the square number of the bracketing piece."
287   (declare (type board board)
288            (type square square)
289            (type player player)
290            (type dir dir)
291            (optimize (speed 3) (safety 0))
292 )
293   (cond ((= (bref board square) player) square)
294         ((= (bref board square) (the player (opponent player)))
295          (find-bracketing-piece (the square (+ square dir)) player board dir))
296         (t nil)))
297
298 (defun next-to-play (board previous-player &optional (print nil))
299   "Compute the player to move next, or NIL if nobody can move."
300   (declare (type board board)
301            (type player previous-player)
302            (type boolean print))
303   (let ((opp (opponent previous-player)))
304     (cond ((any-legal-move? opp board) opp)
305           ((any-legal-move? previous-player board) 
306            (when print
307              (format t "~&~c has no moves and must pass."
308                      (name-of opp)))
309            previous-player)
310           (t nil))))
311
312 (defun any-legal-move? (player board)
313   "Does player have any legal moves in this position?"
314   (declare (type player player)
315            (type board board))
316   (some #'(lambda (move) (declare (type move move)) (legal-p move player board))
317         all-squares))
318
319
320 (defun legal-moves (player board)
321   "Returns a list of legal moves for player"
322   ;;*** fix, segre, 3/30/93.  Was remove-if, which can share with all-squares.
323   (declare (type player player)
324            (type board board))
325   (loop for move in all-squares
326       when (legal-p move player board) collect move))
327
328 #-allegro
329 (defun replace-board (to from)
330   (replace to from))
331
332 #+allegro
333 (defun replace-board (to from)
334   (declare (type board to from))
335   (ff::fslot-memory-copy to 0 400 from)
336   to)
337
338 (defvar *ply-boards*
339   (apply #'vector (loop repeat 40 collect (initial-board))))
340
341
342 (defvar *move-number* 1 "The number of the move to be played")
343 (declaim (type fixnum *move-number*))
344
345 (defun make-game (bl-strategy wh-strategy 
346                   &key 
347                   (print t) 
348                   (minutes +default-max-minutes+)
349                   (record-game nil))
350   (let ((game
351          (make-instance 'reversi-game :bl-strategy bl-strategy
352                         :wh-strategy wh-strategy
353                         :print? print
354                         :record-game? record-game
355                         :max-minutes minutes)))
356     (setf (clock game) (make-clock minutes))
357     game))
358
359 (defun play-game (game)
360   (catch 'game-over
361     (until (null (player game))
362            (setq *move-number* (move-number game))
363            (get-move game
364                      (if (= (player game) black) 
365                          (bl-strategy game)
366                        (wh-strategy game))
367                      (player game)
368                      (board game) (print? game) (clock game))
369            (setf (player game) 
370              (next-to-play (board game) (player game) (print? game)))
371            (incf (move-number game))))
372   (when (print? game)
373     (format t "~&The game is over.  Final result:")
374     (print-board (board game) (clock game)))
375   (count-difference black (board game)))
376
377
378 (defun reversi (bl-strategy wh-strategy 
379                 &optional (print t) (minutes +default-max-minutes+))
380   (play-game (make-game bl-strategy wh-strategy :print print
381                         :record-game nil :minutes minutes)))
382
383 (defvar *clock* (make-clock +default-max-minutes+) "A copy of the game clock")
384 (defvar *board* (initial-board) "A copy of the game board")
385
386 (defun get-move (game strategy player board print clock)
387   "Call the player's strategy function to get a move.
388   Keep calling until a legal move is made."
389   ;; Note we don't pass the strategy function the REAL board.
390   ;; If we did, it could cheat by changing the pieces on the board.
391   (when print (print-board board clock))
392   (replace *clock* clock)
393   (let* ((t0 (get-internal-real-time))
394          (move (funcall strategy player (replace-board *board* board)))
395          (t1 (get-internal-real-time)))
396     (decf (elt clock player) (- t1 t0))
397     (cond
398       ((< (elt clock player) 0)
399        (format t "~&~c has no time left and forfeits."
400                (name-of player))
401        (throw 'game-over (if (eql player black) -64 64)))
402       ((eq move 'resign)
403        (throw 'game-over (if (eql player black) -64 64)))
404       ((and (valid-p move) (legal-p move player board))
405        (when print
406          (format t "~&~c moves to ~a." 
407                  (name-of player) (88->h8 move)))
408        (make-game-move game move player))
409       (t (warn "Illegal move: ~a" (88->h8 move))
410          (get-move game strategy player board print clock)))))
411
412
413 (defun random-reversi-series (strategy1 strategy2 
414                               n-pairs &optional (n-random 10))
415   "Play a series of 2*n games, starting from a random position."
416   (reversi-series
417     (switch-strategies #'random-strategy n-random strategy1)
418     (switch-strategies #'random-strategy n-random strategy2)
419     n-pairs))
420
421 (defun switch-strategies (strategy1 m strategy2)
422   "Make a new strategy that plays strategy1 for m moves,
423   then plays according to strategy2."
424   #'(lambda (player board)
425       (funcall (if (<= *move-number* m) strategy1 strategy2)
426                player board)))
427
428 (defun reversi-series (strategy1 strategy2 n-pairs)
429   "Play a series of 2*n-pairs games, swapping sides."
430   (let ((scores
431           (loop repeat n-pairs
432              for random-state = (make-random-state)
433              collect (reversi strategy1 strategy2 nil)
434              do (setf *random-state* random-state)
435              collect (- (reversi strategy2 strategy1 nil)))))
436     ;; Return the number of wins (1/2 for a tie),
437     ;; the total of the point differences, and the
438     ;; scores themselves, all from strategy1's point of view.
439     (values (+ (count-if #'plusp scores)
440                (/ (count-if #'zerop scores) 2))
441             (apply #'+ scores)
442             scores)))
443
444 (defun round-robin (strategies n-pairs &optional
445                     (n-random 10) (names strategies))
446   "Play a tournament among the strategies.
447   N-PAIRS = games each strategy plays as each color against
448   each opponent.  So with N strategies, a total of
449   N*(N-1)*N-PAIRS games are played."
450   (let* ((N (length strategies))
451          (totals (make-array N :initial-element 0))
452          (scores (make-array (list N N)
453                              :initial-element 0)))
454     ;; Play the games
455     (dotimes (i N)
456       (loop for j from (+ i 1) to (- N 1) do 
457           (let* ((wins (random-reversi-series
458                          (elt strategies i)
459                          (elt strategies j)
460                          n-pairs n-random))
461                  (losses (- (* 2 n-pairs) wins)))
462             (incf (aref scores i j) wins)
463             (incf (aref scores j i) losses)
464             (incf (aref totals i) wins)
465             (incf (aref totals j) losses))))
466     ;; Print the results
467     (dotimes (i N)
468       (format t "~&~a~20T ~4f: " (elt names i) (elt totals i))
469       (dotimes (j N)
470         (format t "~4f " (if (eql i j) '---
471                            (aref scores i j)))))))
472