r5103: *** 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.4 2003/06/12 12:42:13 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) (char ".@O?" piece))
104 (defun title-of (piece) (nth (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 fixum from 11 to 88 when (<= 1 (mod i 10) 8) collect i)
114   "A list of all squares")
115
116 (defun initial-board ()
117   "Return a board, empty except for four pieces in the middle."
118   ;; Boards are 100-element vectors, with elements 11-88 used,
119   ;; and the others marked with the sentinel OUTER.  Initially
120   ;; the 4 center squares are taken, the others empty.
121   (let ((board (make-array 100 :element-type 'fixnum
122                            :initial-element outer
123                            :adjustable nil :fill-pointer nil)))
124     (declare (type board board))
125     (dolist (square all-squares)
126       (declare (fixnum square))
127       (setf (bref board square) empty))
128     (setf (bref board 44) white   (bref board 45) black
129           (bref board 54) black   (bref board 55) white)
130     board))
131
132 (defun copy-board (board)
133   (copy-seq board))
134
135 (defgeneric make-clock (clock))
136 (defmethod make-clock ((clock array))
137   (make-array (+ 1 (max black white))
138               :element-type 'integer
139               :initial-contents clock
140               :adjustable nil
141               :fill-pointer nil))
142
143 (defmethod make-clock ((minutes integer))
144   (make-array (+ 1 (max black white))
145               :element-type 'integer
146               :initial-element 
147               (* minutes 60 
148                  internal-time-units-per-second)
149               :adjustable nil
150               :fill-pointer nil))
151
152 (defun count-difference (player board)
153   "Count player's pieces minus opponent's pieces."
154   (declare (type board board)
155            (fixnum player)
156            (optimize (speed 3) (safety 0) (space 0)))
157   (the fixnum (- (the fixnum (count player board))
158                  (the fixum (count (opponent player) board)))))
159
160 (defun valid-p (move)
161   (declare (type move move)
162            (optimize (speed 3) (safety 0) (space 0)))
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) (space 0)))
205   (if (= (the piece (bref board move)) empty)
206       (block search
207         (dolist (dir +all-directions+)
208           (declare (type dir dir))
209           (when (would-flip? move player board dir)
210             (return-from search t)))
211         (return-from search nil))
212     nil))
213
214 (defstruct (state (:constructor make-state-struct))
215   move player board clock)
216
217 (defun make-state (move player clock board)
218   (make-state-struct :move move :player player :clock (make-clock clock) :board (copy-board board)))
219
220 (defun make-game-move (game move player)
221   (when (record-game? game)
222     (vector-push (make-state move player (clock game) (board game))
223                  (moves game)))
224   (make-move move player (board game))
225   (incf (move-number game)))
226
227 (defun reset-game (game &optional (move-number 1))
228   (if (record-game? game)
229       (when (< move-number (move-number game))
230         (let ((old-state (aref (moves game) (1- move-number))))
231           (if old-state
232               (progn
233                 (setf (player game) (state-player old-state))
234                 (replace-board (board game) (state-board old-state))
235                 (replace (clock game) (state-clock old-state))
236                 (setf (fill-pointer (moves game)) (1- move-number))
237                 (setf (move-number game) move-number))
238             (warn "Couldn't find old state"))))
239   (warn "Tried to reset game, but game is not being recorded")))
240   
241 (defun make-move (move player board)
242   "Update board to reflect move by player"
243   ;; First make the move, then make any flips
244   (declare (type board board)
245            (type move move)
246            (type player)
247            (optimize (speed 3) (safety 0) (space 0)))
248   (setf (bref board move) player)
249   (dolist (dir +all-directions+)
250     (declare (type dir dir))
251     (make-flips move player board dir))
252   board)
253
254 (defun make-flips (move player board dir)
255   "Make any flips in the given direction."
256   (declare (type board board)
257            (type move move)
258            (type player player)
259            (type dir dir)
260            (optimize (speed 3) (safety 0) (space 0)))
261   (let ((bracketer (would-flip? move player board dir)))
262     (when bracketer
263       (loop for c from (+ move dir) by dir until (= c (the fixnum bracketer))
264             do (setf (bref board c) player)))))
265
266 (defun would-flip? (move player board dir)
267   "Would this move result in any flips in this direction?
268   If so, return the square number of the bracketing piece."
269   ;; A flip occurs if, starting at the adjacent square, c, there
270   ;; is a string of at least one opponent pieces, bracketed by 
271   ;; one of player's pieces
272   (declare (type board board)
273            (type move move)
274            (type player player)
275            (type dir dir)
276            (optimize (speed 3) (safety 0) (space 0)))
277   (let ((c (+ move dir)))
278     (declare (type square c))
279     (and (= (the piece (bref board c)) (the player (opponent player)))
280          (find-bracketing-piece (+ c dir) player board dir))))
281
282 (defun find-bracketing-piece (square player board dir)
283   "Return the square number of the bracketing piece."
284   (declare (type board board)
285            (type square square)
286            (type player player)
287            (type dir dir)
288            (optimize (speed 3) (safety 0))
289 )
290   (cond ((= (bref board square) player) square)
291         ((= (bref board square) (the player (opponent player)))
292          (find-bracketing-piece (the square (+ square dir)) player board dir))
293         (t nil)))
294
295 (defun next-to-play (board previous-player &optional (print nil))
296   "Compute the player to move next, or NIL if nobody can move."
297   (declare (type board board)
298            (type player previous-player)
299            (type boolean print))
300   (let ((opp (opponent previous-player)))
301     (cond ((any-legal-move? opp board) opp)
302           ((any-legal-move? previous-player board) 
303            (when print
304              (format t "~&~c has no moves and must pass."
305                      (name-of opp)))
306            previous-player)
307           (t nil))))
308
309 (defun any-legal-move? (player board)
310   "Does player have any legal moves in this position?"
311   (declare (type player player)
312            (type board board))
313   (some #'(lambda (move) (declare (type move move)) (legal-p move player board))
314         all-squares))
315
316
317 (defun legal-moves (player board)
318   "Returns a list of legal moves for player"
319   ;;*** fix, segre, 3/30/93.  Was remove-if, which can share with all-squares.
320   (declare (type player player)
321            (type board board))
322   (loop for move in all-squares
323       when (legal-p move player board) collect move))
324
325 #-allegro
326 (defun replace-board (to from)
327   (replace to from))
328
329 #+allegro
330 (defun replace-board (to from)
331   (declare (type board to from))
332   (ff::fslot-memory-copy to 0 400 from)
333   to)
334
335 (defvar *ply-boards*
336   (apply #'vector (loop repeat 40 collect (initial-board))))
337
338
339 (defvar *move-number* 1 "The number of the move to be played")
340 (declaim (type fixnum *move-number*))
341
342 (defun make-game (bl-strategy wh-strategy 
343                   &key 
344                   (print t) 
345                   (minutes +default-max-minutes+)
346                   (record-game nil))
347   (let ((game
348          (make-instance 'reversi-game :bl-strategy bl-strategy
349                         :wh-strategy wh-strategy
350                         :print? print
351                         :record-game? record-game
352                         :max-minutes minutes)))
353     (setf (clock game) (make-clock minutes))
354     game))
355
356 (defun play-game (game)
357   (catch 'game-over
358     (until (null (player game))
359            (setq *move-number* (move-number game))
360            (get-move game
361                      (if (= (player game) black) 
362                          (bl-strategy game)
363                        (wh-strategy game))
364                      (player game)
365                      (board game) (print? game) (clock game))
366            (setf (player game) 
367              (next-to-play (board game) (player game) (print? game)))
368            (incf (move-number game))))
369   (when (print? game)
370     (format t "~&The game is over.  Final result:")
371     (print-board (board game) (clock game)))
372   (count-difference black (board game)))
373
374
375 (defun reversi (bl-strategy wh-strategy 
376                 &optional (print t) (minutes +default-max-minutes+))
377   (play-game (make-game bl-strategy wh-strategy :print print
378                         :record-game nil :minutes minutes)))
379
380 (defvar *clock* (make-clock +default-max-minutes+) "A copy of the game clock")
381 (defvar *board* (initial-board) "A copy of the game board")
382
383 (defun get-move (game strategy player board print clock)
384   "Call the player's strategy function to get a move.
385   Keep calling until a legal move is made."
386   ;; Note we don't pass the strategy function the REAL board.
387   ;; If we did, it could cheat by changing the pieces on the board.
388   (when print (print-board board clock))
389   (replace *clock* clock)
390   (let* ((t0 (get-internal-real-time))
391          (move (funcall strategy player (replace-board *board* board)))
392          (t1 (get-internal-real-time)))
393     (decf (elt clock player) (- t1 t0))
394     (cond
395       ((< (elt clock player) 0)
396        (format t "~&~c has no time left and forfeits."
397                (name-of player))
398        (throw 'game-over (if (eql player black) -64 64)))
399       ((eq move 'resign)
400        (throw 'game-over (if (eql player black) -64 64)))
401       ((and (valid-p move) (legal-p move player board))
402        (when print
403          (format t "~&~c moves to ~a." 
404                  (name-of player) (88->h8 move)))
405        (make-game-move game move player))
406       (t (warn "Illegal move: ~a" (88->h8 move))
407          (get-move game strategy player board print clock)))))
408
409
410 (defun random-reversi-series (strategy1 strategy2 
411                               n-pairs &optional (n-random 10))
412   "Play a series of 2*n games, starting from a random position."
413   (reversi-series
414     (switch-strategies #'random-strategy n-random strategy1)
415     (switch-strategies #'random-strategy n-random strategy2)
416     n-pairs))
417
418 (defun switch-strategies (strategy1 m strategy2)
419   "Make a new strategy that plays strategy1 for m moves,
420   then plays according to strategy2."
421   #'(lambda (player board)
422       (funcall (if (<= *move-number* m) strategy1 strategy2)
423                player board)))
424
425 (defun reversi-series (strategy1 strategy2 n-pairs)
426   "Play a series of 2*n-pairs games, swapping sides."
427   (let ((scores
428           (loop repeat n-pairs
429              for random-state = (make-random-state)
430              collect (reversi strategy1 strategy2 nil)
431              do (setf *random-state* random-state)
432              collect (- (reversi strategy2 strategy1 nil)))))
433     ;; Return the number of wins (1/2 for a tie),
434     ;; the total of the point differences, and the
435     ;; scores themselves, all from strategy1's point of view.
436     (values (+ (count-if #'plusp scores)
437                (/ (count-if #'zerop scores) 2))
438             (apply #'+ scores)
439             scores)))
440
441 (defun round-robin (strategies n-pairs &optional
442                     (n-random 10) (names strategies))
443   "Play a tournament among the strategies.
444   N-PAIRS = games each strategy plays as each color against
445   each opponent.  So with N strategies, a total of
446   N*(N-1)*N-PAIRS games are played."
447   (let* ((N (length strategies))
448          (totals (make-array N :initial-element 0))
449          (scores (make-array (list N N)
450                              :initial-element 0)))
451     ;; Play the games
452     (dotimes (i N)
453       (loop for j from (+ i 1) to (- N 1) do 
454           (let* ((wins (random-reversi-series
455                          (elt strategies i)
456                          (elt strategies j)
457                          n-pairs n-random))
458                  (losses (- (* 2 n-pairs) wins)))
459             (incf (aref scores i j) wins)
460             (incf (aref scores j i) losses)
461             (incf (aref totals i) wins)
462             (incf (aref totals j) losses))))
463     ;; Print the results
464     (dotimes (i N)
465       (format t "~&~a~20T ~4f: " (elt names i) (elt totals i))
466       (dotimes (j N)
467         (format t "~4f " (if (eql i j) '---
468                            (aref scores i j)))))))
469