Fix types/initforms
[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 ;;;; This file is Copyright (c) 2001-2002 by Kevin M. Rosenberg
12 ;;;; and Copyright (c) 1998-2002 Peter Norvig
13 ;;;;
14 ;;;; Reversi users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;;***************************************************************************
18
19 (in-package #:reversi)
20
21 (defparameter +all-directions+ '(-11 -10 -9 -1 1 9 10 11))
22 (defconstant +default-max-minutes+ 30)
23
24 (defconstant empty 0 "An empty square")
25 (defconstant black 1 "A black piece")
26 (defconstant white 2 "A white piece")
27 (defconstant outer 3 "Marks squares outside the 8x8 board")
28 ;;(declaim (type (unsigned-byte 8) empty black white outer))
29 (declaim (type fixnum empty black white outer))
30
31 #|
32 (deftype piece () '(unsigned-byte 8))
33 (deftype player () '(unsigned-byte 8))
34 (deftype move () '(unsigned-byte 8))
35 (deftype square () '(unsigned-byte 8))
36 |#
37
38 (deftype piece () 'fixnum)
39 (deftype player () 'fixnum)
40 (deftype move () 'fixnum)
41 (deftype square () 'fixnum)
42 (deftype dir () 'fixnum)
43 (deftype board () '(simple-array fixnum (100)))
44 ;;(deftype board () '(simple-array (unsigned-byte 8) (100)))
45 (deftype clock () '(simple-array integer (3)))
46
47 (defun make-moves ()
48   (make-array 60 :element-type 'cons :fill-pointer 0
49               :adjustable nil :initial-element (cons nil nil)))
50 (deftype moves () '(array cons (60)))
51
52
53 (defclass reversi-game ()
54   ((bl-strategy :initarg :bl-strategy
55                 :documentation "Strategy function for black"
56                 :reader bl-strategy)
57    (wh-strategy :initarg :wh-strategy
58                 :documentation "Strategy function for white"
59                 :reader wh-strategy)
60    (board :type board :initarg :board
61           :documentation "The board configuration"
62           :reader board)
63    (move-number :type fixnum :initarg :move-number
64                 :documentation "The number of the move to be played"
65                 :accessor move-number)
66    (player :type player :initarg :player
67                 :documentation "ID of next player to move"
68                 :accessor player)
69    (moves :type moves :initarg :moves
70           :documentation "An array of moves played in the game"
71           :accessor moves)
72    (print? :type boolean :initarg :print?
73            :documentation "Whether to print progress of this game"
74            :reader print?)
75    (record-game? :type boolean :initarg :record-game?
76            :documentation "Whether to record moves and clcck of this game"
77            :reader record-game?)
78    (final-result :type (or null fixnum) :initarg :final-result
79                  :documentation "Final count, is NIL while game in play"
80                  :accessor final-result)
81    (max-minutes :type fixnum :initarg :max-minutes
82                 :documentation "Maximum minites for each player"
83                 :reader max-minutes)
84    (clock :type clock :initarg :clock
85           :documentation "An array of time-units left"
86           :accessor clock))
87   (:default-initargs
88       :bl-strategy nil
89     :wh-strategy nil
90     :board (initial-board)
91     :move-number 1
92     :player black
93     :moves (make-moves)
94     :print? nil
95     :record-game? nil
96     :final-result nil
97     :max-minutes +default-max-minutes+
98     :clock (make-clock +default-max-minutes+)))
99
100
101 (defun name-of (piece) (schar ".@O?" piece))
102 (defun title-of (piece)
103   (declare (fixnum piece))
104   (nth (the fixnum (1- piece)) '("Black" "White")) )
105
106 (defmacro opponent (player)
107   `(if (= ,player black) white black))
108
109 (defmacro bref (board square)
110   `(the piece (aref (the board ,board) (the square ,square))))
111
112 (defparameter all-squares
113     (loop for i fixnum from 11 to 88
114           when (<= 1 (the fixnum (mod i 10)) 8)
115           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            (type fixnum player)
158            (optimize (speed 3) (safety 0) (space 0)))
159   (the fixnum (- (the fixnum (count player board))
160                  (the fixnum (count (opponent player) board)))))
161
162 (defun valid-p (move)
163   (declare (type move move)
164            (optimize (speed 3) (safety 0) (space 0)))
165   "Valid moves are numbers in the range 11-88 that end in 1-8."
166   (and (typep move 'move) (<= 11 move 88) (<= 1 (mod move 10) 8)))
167
168 #+ignore
169 (defun legal-p (move player board)
170   "A Legal move must be into an empty square, and it must
171   flip at least one opponent piece."
172   (declare (type board board)
173            (type move move)
174            (type player player))
175   (and (= (the piece (bref board move)) empty)
176        (some #'(lambda (dir) (declare (type dir dir)) (would-flip? move player board dir))
177              +all-directions+)))
178
179 #+ignore
180 (defun legal-p (move player board)
181   "A Legal move must be into an empty square, and it must
182   flip at least one opponent piece."
183   (declare (type board board)
184            (type move move)
185            (type player player)
186            (optimize speed (safety 0) (space 0)))
187   (if (= (bref board move) empty)
188       (block search
189         (let ((i 0))
190           (declare (fixnum i))
191           (tagbody t
192             (when (>= i 8) (return-from search nil))
193             (when (would-flip? move player board (aref +all-directions+ i))
194               (return-from search t))
195             (incf i)
196             (go t))))
197     nil))
198
199 (defun legal-p (move player board)
200   "A Legal move must be into an empty square, and it must
201   flip at least one opponent piece."
202   (declare (type board board)
203            (type move move)
204            (type player player)
205            (optimize (speed 3) (safety 0) (space 0)))
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) (space 0)))
249   (setf (bref board move) player)
250   (dolist (dir +all-directions+)
251     (declare (type dir dir))
252     (make-flips move player board dir))
253   board)
254
255 (defun make-flips (move player board dir)
256   "Make any flips in the given direction."
257   (declare (type board board)
258            (type move move)
259            (type player player)
260            (type dir dir)
261            (optimize (speed 3) (safety 0) (space 0)))
262   (let ((bracketer (would-flip? move player board dir)))
263     (when bracketer
264       (loop for c from (+ move dir) by dir until (= c (the fixnum bracketer))
265             do (setf (bref board c) player)))))
266
267 (defun would-flip? (move player board dir)
268   "Would this move result in any flips in this direction?
269   If so, return the square number of the bracketing piece."
270   ;; A flip occurs if, starting at the adjacent square, c, there
271   ;; is a string of at least one opponent pieces, bracketed by
272   ;; one of player's pieces
273   (declare (type board board)
274            (type move move)
275            (type player player)
276            (type dir dir)
277            (optimize (speed 3) (safety 0) (space 0)))
278   (let ((c (+ move dir)))
279     (declare (type square c))
280     (and (= (the piece (bref board c)) (the player (opponent player)))
281          (find-bracketing-piece (the fixnum (+ c dir)) player board dir))))
282
283 (defun find-bracketing-piece (square player board dir)
284   "Return the square number of the bracketing piece."
285   (declare (type board board)
286            (type square square)
287            (type player player)
288            (type dir dir)
289            (optimize (speed 3) (safety 0))
290 )
291   (cond ((= (bref board square) player) square)
292         ((= (bref board square) (the player (opponent player)))
293          (find-bracketing-piece (the square (+ square dir)) player board dir))
294         (t nil)))
295
296 (defun next-to-play (board previous-player &optional (print nil))
297   "Compute the player to move next, or NIL if nobody can move."
298   (declare (type board board)
299            (type player previous-player)
300            (type boolean print))
301   (let ((opp (opponent previous-player)))
302     (cond ((any-legal-move? opp board) opp)
303           ((any-legal-move? previous-player board)
304            (when print
305              (format t "~&~c has no moves and must pass."
306                      (name-of opp)))
307            previous-player)
308           (t nil))))
309
310 (defun any-legal-move? (player board)
311   "Does player have any legal moves in this position?"
312   (declare (type player player)
313            (type board board))
314   (some #'(lambda (move) (declare (type move move)) (legal-p move player board))
315         all-squares))
316
317
318 (defun legal-moves (player board)
319   "Returns a list of legal moves for player"
320   ;;*** fix, segre, 3/30/93.  Was remove-if, which can share with all-squares.
321   (declare (type player player)
322            (type board board))
323   (loop for move in all-squares
324       when (legal-p move player board) collect move))
325
326 (defun replace-board (to from)
327   (replace to from))
328
329 (defvar *ply-boards*
330   (apply #'vector (loop repeat 40 collect (initial-board))))
331
332
333 (defvar *move-number* 1 "The number of the move to be played")
334 (declaim (type fixnum *move-number*))
335
336 (defun make-game (bl-strategy wh-strategy
337                   &key
338                   (print t)
339                   (minutes +default-max-minutes+)
340                   (record-game nil))
341   (let ((game
342          (make-instance 'reversi-game :bl-strategy bl-strategy
343                         :wh-strategy wh-strategy
344                         :print? print
345                         :record-game? record-game
346                         :max-minutes minutes)))
347     (setf (clock game) (make-clock minutes))
348     game))
349
350 (defun play-game (game)
351   (catch 'game-over
352     (until (null (player game))
353            (setq *move-number* (move-number game))
354            (get-move game
355                      (if (= (player game) black)
356                          (bl-strategy game)
357                        (wh-strategy game))
358                      (player game)
359                      (board game) (print? game) (clock game))
360            (setf (player game)
361              (next-to-play (board game) (player game) (print? game)))
362            (incf (move-number game))))
363   (when (print? game)
364     (format t "~&The game is over.  Final result:")
365     (print-board (board game) (clock game)))
366   (count-difference black (board game)))
367
368
369 (defun reversi (bl-strategy wh-strategy
370                 &optional (print t) (minutes +default-max-minutes+))
371   (play-game (make-game bl-strategy wh-strategy :print print
372                         :record-game nil :minutes minutes)))
373
374 (defvar *clock* (make-clock +default-max-minutes+) "A copy of the game clock")
375 (defvar *board* (initial-board) "A copy of the game board")
376
377 (defun get-move (game strategy player board print clock)
378   "Call the player's strategy function to get a move.
379   Keep calling until a legal move is made."
380   ;; Note we don't pass the strategy function the REAL board.
381   ;; If we did, it could cheat by changing the pieces on the board.
382   (when print (print-board board clock))
383   (replace *clock* clock)
384   (let* ((t0 (get-internal-real-time))
385          (move (funcall strategy player (replace-board *board* board)))
386          (t1 (get-internal-real-time)))
387     (decf (elt clock player) (- t1 t0))
388     (cond
389       ((< (elt clock player) 0)
390        (format t "~&~c has no time left and forfeits."
391                (name-of player))
392        (throw 'game-over (if (eql player black) -64 64)))
393       ((eq move 'resign)
394        (throw 'game-over (if (eql player black) -64 64)))
395       ((and (valid-p move) (legal-p move player board))
396        (when print
397          (format t "~&~c moves to ~a."
398                  (name-of player) (88->h8 move)))
399        (make-game-move game move player))
400       (t (warn "Illegal move: ~a" (88->h8 move))
401          (get-move game strategy player board print clock)))))
402
403
404 (defun random-reversi-series (strategy1 strategy2
405                               n-pairs &optional (n-random 10))
406   "Play a series of 2*n games, starting from a random position."
407   (reversi-series
408     (switch-strategies #'random-strategy n-random strategy1)
409     (switch-strategies #'random-strategy n-random strategy2)
410     n-pairs))
411
412 (defun switch-strategies (strategy1 m strategy2)
413   "Make a new strategy that plays strategy1 for m moves,
414   then plays according to strategy2."
415   #'(lambda (player board)
416       (funcall (if (<= *move-number* m) strategy1 strategy2)
417                player board)))
418
419 (defun reversi-series (strategy1 strategy2 n-pairs)
420   "Play a series of 2*n-pairs games, swapping sides."
421   (let ((scores
422           (loop repeat n-pairs
423              for random-state = (make-random-state)
424              collect (reversi strategy1 strategy2 nil)
425              do (setf *random-state* random-state)
426              collect (- (reversi strategy2 strategy1 nil)))))
427     ;; Return the number of wins (1/2 for a tie),
428     ;; the total of the point differences, and the
429     ;; scores themselves, all from strategy1's point of view.
430     (values (+ (count-if #'plusp scores)
431                (/ (count-if #'zerop scores) 2))
432             (apply #'+ scores)
433             scores)))
434
435 (defun round-robin (strategies n-pairs &optional
436                     (n-random 10) (names strategies))
437   "Play a tournament among the strategies.
438   N-PAIRS = games each strategy plays as each color against
439   each opponent.  So with N strategies, a total of
440   N*(N-1)*N-PAIRS games are played."
441   (let* ((N (length strategies))
442          (totals (make-array N :initial-element 0))
443          (scores (make-array (list N N)
444                              :initial-element 0)))
445     ;; Play the games
446     (dotimes (i N)
447       (loop for j from (+ i 1) to (- N 1) do
448           (let* ((wins (random-reversi-series
449                          (elt strategies i)
450                          (elt strategies j)
451                          n-pairs n-random))
452                  (losses (- (* 2 n-pairs) wins)))
453             (incf (aref scores i j) wins)
454             (incf (aref scores j i) losses)
455             (incf (aref totals i) wins)
456             (incf (aref totals j) losses))))
457     ;; Print the results
458     (dotimes (i N)
459       (format t "~&~a~20T ~4f: " (elt names i) (elt totals i))
460       (dotimes (j N)
461         (format t "~4f " (if (eql i j) '---
462                            (aref scores i j)))))))