Update FSF's address.
[bpt/emacs.git] / lisp / play / gomoku.el
1 ;;; gomoku.el --- Gomoku game between you and Emacs
2
3 ;; Copyright (C) 1988, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Philippe Schnoebelen <phs@lifia.imag.fr>
6 ;; Adapted-By: ESR
7 ;; Keywords: games
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; Gomoku game between you and GNU Emacs. Last modified on 13 Sep 1988
29 ;;
30 ;; Written by Ph. Schnoebelen (phs@lifia.imag.fr), 1987, 1988
31 ;; with precious advices from J.-F. Rit.
32 ;; This has been tested with GNU Emacs 18.50.
33
34 ;; RULES:
35 ;;
36 ;; Gomoku is a game played between two players on a rectangular board. Each
37 ;; player, in turn, marks a free square of its choice. The winner is the first
38 ;; one to mark five contiguous squares in any direction (horizontally,
39 ;; vertically or diagonally).
40 ;;
41 ;; I have been told that, in "The TRUE Gomoku", some restrictions are made
42 ;; about the squares where one may play, or else there is a known forced win
43 ;; for the first player. This program has no such restriction, but it does not
44 ;; know about the forced win, nor do I. Furthermore, you probably do not know
45 ;; it yourself :-).
46
47
48 ;; There are two main places where you may want to customize the program: key
49 ;; bindings and board display. These features are commented in the code. Go
50 ;; and see.
51
52
53 ;; HOW TO USE:
54 ;;
55 ;; The command "M-x gomoku" displays a
56 ;; board, the size of which depends on the size of the current window. The
57 ;; size of the board is easily modified by giving numeric arguments to the
58 ;; gomoku command and/or by customizing the displaying parameters.
59 ;;
60 ;; Emacs plays when it is its turn. When it is your turn, just put the cursor
61 ;; on the square where you want to play and hit RET, or X, or whatever key you
62 ;; bind to the command gomoku-human-plays. When it is your turn, Emacs is
63 ;; idle: you may switch buffers, read your mail, ... Just come back to the
64 ;; *Gomoku* buffer and resume play.
65
66
67 ;; ALGORITHM:
68 ;;
69 ;; The algorithm is briefly described in section "THE SCORE TABLE". Some
70 ;; parameters may be modified if you want to change the style exhibited by the
71 ;; program.
72
73 ;;; Code:
74 \f
75 ;;;
76 ;;; GOMOKU MODE AND KEYMAP.
77 ;;;
78 (defvar gomoku-mode-hook nil
79 "If non-nil, its value is called on entry to Gomoku mode.")
80
81 (defvar gomoku-mode-map nil
82 "Local keymap to use in Gomoku mode.")
83
84 (if gomoku-mode-map nil
85 (setq gomoku-mode-map (make-sparse-keymap))
86
87 ;; Key bindings for cursor motion. Arrow keys are just "function"
88 ;; keys, see below.
89 (define-key gomoku-mode-map "y" 'gomoku-move-nw) ; Y
90 (define-key gomoku-mode-map "u" 'gomoku-move-ne) ; U
91 (define-key gomoku-mode-map "b" 'gomoku-move-sw) ; B
92 (define-key gomoku-mode-map "n" 'gomoku-move-se) ; N
93 (define-key gomoku-mode-map "h" 'gomoku-move-left) ; H
94 (define-key gomoku-mode-map "l" 'gomoku-move-right) ; L
95 (define-key gomoku-mode-map "j" 'gomoku-move-down) ; J
96 (define-key gomoku-mode-map "k" 'gomoku-move-up) ; K
97 (define-key gomoku-mode-map "\C-n" 'gomoku-move-down) ; C-N
98 (define-key gomoku-mode-map "\C-p" 'gomoku-move-up) ; C-P
99 (define-key gomoku-mode-map "\C-f" 'gomoku-move-right) ; C-F
100 (define-key gomoku-mode-map "\C-b" 'gomoku-move-left) ; C-B
101
102 ;; Key bindings for entering Human moves.
103 ;; If you have a mouse, you may also bind some mouse click ...
104 (define-key gomoku-mode-map "X" 'gomoku-human-plays) ; X
105 (define-key gomoku-mode-map "x" 'gomoku-human-plays) ; x
106 (define-key gomoku-mode-map "\C-m" 'gomoku-human-plays) ; RET
107 (define-key gomoku-mode-map "\C-c\C-p" 'gomoku-human-plays) ; C-C C-P
108 (define-key gomoku-mode-map "\C-c\C-b" 'gomoku-human-takes-back) ; C-C C-B
109 (define-key gomoku-mode-map "\C-c\C-r" 'gomoku-human-resigns) ; C-C C-R
110 (define-key gomoku-mode-map "\C-c\C-e" 'gomoku-emacs-plays) ; C-C C-E
111
112 (define-key gomoku-mode-map [up] 'gomoku-move-up)
113 (define-key gomoku-mode-map [down] 'gomoku-move-down)
114 (define-key gomoku-mode-map [left] 'gomoku-move-left)
115 (define-key gomoku-mode-map [right] 'gomoku-move-right)
116 (define-key gomoku-mode-map [kp-enter] 'gomoku-human-plays)
117 (define-key gomoku-mode-map [mouse-2] 'gomoku-click)
118 (define-key gomoku-mode-map [insert] 'gomoku-human-plays))
119
120 (defun gomoku-mode ()
121 "Major mode for playing Gomoku against Emacs.
122 You and Emacs play in turn by marking a free square. You mark it with X
123 and Emacs marks it with O. The winner is the first to get five contiguous
124 marks horizontally, vertically or in diagonal.
125
126 You play by moving the cursor over the square you choose and hitting \\[gomoku-human-plays].
127
128 Other useful commands:
129 \\{gomoku-mode-map}
130 Entry to this mode calls the value of `gomoku-mode-hook' if that value
131 is non-nil."
132 (interactive)
133 (setq major-mode 'gomoku-mode
134 mode-name "Gomoku")
135 (gomoku-display-statistics)
136 (use-local-map gomoku-mode-map)
137 (run-hooks 'gomoku-mode-hook))
138 \f
139 ;;;
140 ;;; THE BOARD.
141 ;;;
142
143 ;; The board is a rectangular grid. We code empty squares with 0, X's with 1
144 ;; and O's with 6. The rectangle is recorded in a one dimensional vector
145 ;; containing padding squares (coded with -1). These squares allow us to
146 ;; detect when we are trying to move out of the board. We denote a square by
147 ;; its (X,Y) coords, or by the INDEX corresponding to them in the vector. The
148 ;; leftmost topmost square has coords (1,1) and index gomoku-board-width + 2.
149 ;; Similarly, vectors between squares may be given by two DX, DY coords or by
150 ;; one DEPL (the difference between indexes).
151
152 (defvar gomoku-board-width nil
153 "Number of columns on the Gomoku board.")
154
155 (defvar gomoku-board-height nil
156 "Number of lines on the Gomoku board.")
157
158 (defvar gomoku-board nil
159 "Vector recording the actual state of the Gomoku board.")
160
161 (defvar gomoku-vector-length nil
162 "Length of gomoku-board vector.")
163
164 (defvar gomoku-draw-limit nil
165 ;; This is usually set to 70% of the number of squares.
166 "After how many moves will Emacs offer a draw?")
167
168
169 (defun gomoku-xy-to-index (x y)
170 "Translate X, Y cartesian coords into the corresponding board index."
171 (+ (* y gomoku-board-width) x y))
172
173 (defun gomoku-index-to-x (index)
174 "Return corresponding x-coord of board INDEX."
175 (% index (1+ gomoku-board-width)))
176
177 (defun gomoku-index-to-y (index)
178 "Return corresponding y-coord of board INDEX."
179 (/ index (1+ gomoku-board-width)))
180
181 (defun gomoku-init-board ()
182 "Create the gomoku-board vector and fill it with initial values."
183 (setq gomoku-board (make-vector gomoku-vector-length 0))
184 ;; Every square is 0 (i.e. empty) except padding squares:
185 (let ((i 0) (ii (1- gomoku-vector-length)))
186 (while (<= i gomoku-board-width) ; The squares in [0..width] and in
187 (aset gomoku-board i -1) ; [length - width - 1..length - 1]
188 (aset gomoku-board ii -1) ; are padding squares.
189 (setq i (1+ i)
190 ii (1- ii))))
191 (let ((i 0))
192 (while (< i gomoku-vector-length)
193 (aset gomoku-board i -1) ; and also all k*(width+1)
194 (setq i (+ i gomoku-board-width 1)))))
195 \f
196 ;;;
197 ;;; THE SCORE TABLE.
198 ;;;
199
200 ;; Every (free) square has a score associated to it, recorded in the
201 ;; GOMOKU-SCORE-TABLE vector. The program always plays in the square having
202 ;; the highest score.
203
204 (defvar gomoku-score-table nil
205 "Vector recording the actual score of the free squares.")
206
207
208 ;; The key point point about the algorithm is that, rather than considering
209 ;; the board as just a set of squares, we prefer to see it as a "space" of
210 ;; internested 5-tuples of contiguous squares (called qtuples).
211 ;;
212 ;; The aim of the program is to fill one qtuple with its O's while preventing
213 ;; you from filling another one with your X's. To that effect, it computes a
214 ;; score for every qtuple, with better qtuples having better scores. Of
215 ;; course, the score of a qtuple (taken in isolation) is just determined by
216 ;; its contents as a set, i.e. not considering the order of its elements. The
217 ;; highest score is given to the "OOOO" qtuples because playing in such a
218 ;; qtuple is winning the game. Just after this comes the "XXXX" qtuple because
219 ;; not playing in it is just loosing the game, and so on. Note that a
220 ;; "polluted" qtuple, i.e. one containing at least one X and at least one O,
221 ;; has score zero because there is no more any point in playing in it, from
222 ;; both an attacking and a defending point of view.
223 ;;
224 ;; Given the score of every qtuple, the score of a given free square on the
225 ;; board is just the sum of the scores of all the qtuples to which it belongs,
226 ;; because playing in that square is playing in all its containing qtuples at
227 ;; once. And it is that function which takes into account the internesting of
228 ;; the qtuples.
229 ;;
230 ;; This algorithm is rather simple but anyway it gives a not so dumb level of
231 ;; play. It easily extends to "n-dimensional Gomoku", where a win should not
232 ;; be obtained with as few as 5 contiguous marks: 6 or 7 (depending on n !)
233 ;; should be preferred.
234
235
236 ;; Here are the scores of the nine "non-polluted" configurations. Tuning
237 ;; these values will change (hopefully improve) the strength of the program
238 ;; and may change its style (rather aggressive here).
239
240 (defconst nil-score 7 "Score of an empty qtuple.")
241 (defconst Xscore 15 "Score of a qtuple containing one X.")
242 (defconst XXscore 400 "Score of a qtuple containing two X's.")
243 (defconst XXXscore 1800 "Score of a qtuple containing three X's.")
244 (defconst XXXXscore 100000 "Score of a qtuple containing four X's.")
245 (defconst Oscore 35 "Score of a qtuple containing one O.")
246 (defconst OOscore 800 "Score of a qtuple containing two O's.")
247 (defconst OOOscore 15000 "Score of a qtuple containing three O's.")
248 (defconst OOOOscore 800000 "Score of a qtuple containing four O's.")
249
250 ;; These values are not just random: if, given the following situation:
251 ;;
252 ;; . . . . . . . O .
253 ;; . X X a . . . X .
254 ;; . . . X . . . X .
255 ;; . . . X . . . X .
256 ;; . . . . . . . b .
257 ;;
258 ;; you want Emacs to play in "a" and not in "b", then the parameters must
259 ;; satisfy the inequality:
260 ;;
261 ;; 6 * XXscore > XXXscore + XXscore
262 ;;
263 ;; because "a" mainly belongs to six "XX" qtuples (the others are less
264 ;; important) while "b" belongs to one "XXX" and one "XX" qtuples. Other
265 ;; conditions are required to obtain sensible moves, but the previous example
266 ;; should illustrate the point. If you manage to improve on these values,
267 ;; please send me a note. Thanks.
268
269
270 ;; As we chose values 0, 1 and 6 to denote empty, X and O squares, the
271 ;; contents of a qtuple are uniquely determined by the sum of its elements and
272 ;; we just have to set up a translation table.
273
274 (defconst gomoku-score-trans-table
275 (vector nil-score Xscore XXscore XXXscore XXXXscore 0
276 Oscore 0 0 0 0 0
277 OOscore 0 0 0 0 0
278 OOOscore 0 0 0 0 0
279 OOOOscore 0 0 0 0 0
280 0)
281 "Vector associating qtuple contents to their score.")
282
283
284 ;; If you do not modify drastically the previous constants, the only way for a
285 ;; square to have a score higher than OOOOscore is to belong to a "OOOO"
286 ;; qtuple, thus to be a winning move. Similarly, the only way for a square to
287 ;; have a score between XXXXscore and OOOOscore is to belong to a "XXXX"
288 ;; qtuple. We may use these considerations to detect when a given move is
289 ;; winning or loosing.
290
291 (defconst gomoku-winning-threshold OOOOscore
292 "Threshold score beyond which an Emacs move is winning.")
293
294 (defconst gomoku-loosing-threshold XXXXscore
295 "Threshold score beyond which a human move is winning.")
296
297
298 (defun gomoku-strongest-square ()
299 "Compute index of free square with highest score, or nil if none."
300 ;; We just have to loop other all squares. However there are two problems:
301 ;; 1/ The SCORE-TABLE only gives correct scores to free squares. To speed
302 ;; up future searches, we set the score of padding or occupied squares
303 ;; to -1 whenever we meet them.
304 ;; 2/ We want to choose randomly between equally good moves.
305 (let ((score-max 0)
306 (count 0) ; Number of equally good moves
307 (square (gomoku-xy-to-index 1 1)) ; First square
308 (end (gomoku-xy-to-index gomoku-board-width gomoku-board-height))
309 best-square score)
310 (while (<= square end)
311 (cond
312 ;; If score is lower (i.e. most of the time), skip to next:
313 ((< (aref gomoku-score-table square) score-max))
314 ;; If score is better, beware of non free squares:
315 ((> (setq score (aref gomoku-score-table square)) score-max)
316 (if (zerop (aref gomoku-board square)) ; is it free ?
317 (setq count 1 ; yes: take it !
318 best-square square
319 score-max score)
320 (aset gomoku-score-table square -1))) ; no: kill it !
321 ;; If score is equally good, choose randomly. But first check freeness:
322 ((not (zerop (aref gomoku-board square)))
323 (aset gomoku-score-table square -1))
324 ((zerop (random (setq count (1+ count))))
325 (setq best-square square
326 score-max score)))
327 (setq square (1+ square))) ; try next square
328 best-square))
329 \f
330 ;;;
331 ;;; INITIALIZING THE SCORE TABLE.
332 ;;;
333
334 ;; At initialization the board is empty so that every qtuple amounts for
335 ;; nil-score. Therefore, the score of any square is nil-score times the number
336 ;; of qtuples that pass through it. This number is 3 in a corner and 20 if you
337 ;; are sufficiently far from the sides. As computing the number is time
338 ;; consuming, we initialize every square with 20*nil-score and then only
339 ;; consider squares at less than 5 squares from one side. We speed this up by
340 ;; taking symmetry into account.
341 ;; Also, as it is likely that successive games will be played on a board with
342 ;; same size, it is a good idea to save the initial SCORE-TABLE configuration.
343
344 (defvar gomoku-saved-score-table nil
345 "Recorded initial value of previous score table.")
346
347 (defvar gomoku-saved-board-width nil
348 "Recorded value of previous board width.")
349
350 (defvar gomoku-saved-board-height nil
351 "Recorded value of previous board height.")
352
353
354 (defun gomoku-init-score-table ()
355 "Create the score table vector and fill it with initial values."
356 (if (and gomoku-saved-score-table ; Has it been stored last time ?
357 (= gomoku-board-width gomoku-saved-board-width)
358 (= gomoku-board-height gomoku-saved-board-height))
359 (setq gomoku-score-table (copy-sequence gomoku-saved-score-table))
360 ;; No, compute it:
361 (setq gomoku-score-table
362 (make-vector gomoku-vector-length (* 20 nil-score)))
363 (let (i j maxi maxj maxi2 maxj2)
364 (setq maxi (/ (1+ gomoku-board-width) 2)
365 maxj (/ (1+ gomoku-board-height) 2)
366 maxi2 (min 4 maxi)
367 maxj2 (min 4 maxj))
368 ;; We took symmetry into account and could use it more if the board
369 ;; would have been square and not rectangular !
370 ;; In our case we deal with all (i,j) in the set [1..maxi2]*[1..maxj] U
371 ;; [maxi2+1..maxi]*[1..maxj2]. Maxi2 and maxj2 are used because the
372 ;; board may well be less than 8 by 8 !
373 (setq i 1)
374 (while (<= i maxi2)
375 (setq j 1)
376 (while (<= j maxj)
377 (gomoku-init-square-score i j)
378 (setq j (1+ j)))
379 (setq i (1+ i)))
380 (while (<= i maxi)
381 (setq j 1)
382 (while (<= j maxj2)
383 (gomoku-init-square-score i j)
384 (setq j (1+ j)))
385 (setq i (1+ i))))
386 (setq gomoku-saved-score-table (copy-sequence gomoku-score-table)
387 gomoku-saved-board-width gomoku-board-width
388 gomoku-saved-board-height gomoku-board-height)))
389
390 (defun gomoku-nb-qtuples (i j)
391 "Return the number of qtuples containing square I,J."
392 ;; This function is complicated because we have to deal
393 ;; with ugly cases like 3 by 6 boards, but it works.
394 ;; If you have a simpler (and correct) solution, send it to me. Thanks !
395 (let ((left (min 4 (1- i)))
396 (right (min 4 (- gomoku-board-width i)))
397 (up (min 4 (1- j)))
398 (down (min 4 (- gomoku-board-height j))))
399 (+ -12
400 (min (max (+ left right) 3) 8)
401 (min (max (+ up down) 3) 8)
402 (min (max (+ (min left up) (min right down)) 3) 8)
403 (min (max (+ (min right up) (min left down)) 3) 8))))
404
405 (defun gomoku-init-square-score (i j)
406 "Give initial score to square I,J and to its mirror images."
407 (let ((ii (1+ (- gomoku-board-width i)))
408 (jj (1+ (- gomoku-board-height j)))
409 (sc (* (gomoku-nb-qtuples i j) (aref gomoku-score-trans-table 0))))
410 (aset gomoku-score-table (gomoku-xy-to-index i j) sc)
411 (aset gomoku-score-table (gomoku-xy-to-index ii j) sc)
412 (aset gomoku-score-table (gomoku-xy-to-index i jj) sc)
413 (aset gomoku-score-table (gomoku-xy-to-index ii jj) sc)))
414 \f
415 ;;;
416 ;;; MAINTAINING THE SCORE TABLE.
417 ;;;
418
419 ;; We do not provide functions for computing the SCORE-TABLE given the
420 ;; contents of the BOARD. This would involve heavy nested loops, with time
421 ;; proportional to the size of the board. It is better to update the
422 ;; SCORE-TABLE after each move. Updating needs not modify more than 36
423 ;; squares: it is done in constant time.
424
425 (defun gomoku-update-score-table (square dval)
426 "Update score table after SQUARE received a DVAL increment."
427 ;; The board has already been updated when this function is called.
428 ;; Updating scores is done by looking for qtuples boundaries in all four
429 ;; directions and then calling update-score-in-direction.
430 ;; Finally all squares received the right increment, and then are up to
431 ;; date, except possibly for SQUARE itself if we are taking a move back for
432 ;; its score had been set to -1 at the time.
433 (let* ((x (gomoku-index-to-x square))
434 (y (gomoku-index-to-y square))
435 (imin (max -4 (- 1 x)))
436 (jmin (max -4 (- 1 y)))
437 (imax (min 0 (- gomoku-board-width x 4)))
438 (jmax (min 0 (- gomoku-board-height y 4))))
439 (gomoku-update-score-in-direction imin imax
440 square 1 0 dval)
441 (gomoku-update-score-in-direction jmin jmax
442 square 0 1 dval)
443 (gomoku-update-score-in-direction (max imin jmin) (min imax jmax)
444 square 1 1 dval)
445 (gomoku-update-score-in-direction (max (- 1 y) -4
446 (- x gomoku-board-width))
447 (min 0 (- x 5)
448 (- gomoku-board-height y 4))
449 square -1 1 dval)))
450
451 (defun gomoku-update-score-in-direction (left right square dx dy dval)
452 "Update scores for all squares in the qtuples starting between the LEFTth
453 square and the RIGHTth after SQUARE, along the DX, DY direction, considering
454 that DVAL has been added on SQUARE."
455 ;; We always have LEFT <= 0, RIGHT <= 0 and DEPL > 0 but we may very well
456 ;; have LEFT > RIGHT, indicating that no qtuple contains SQUARE along that
457 ;; DX,DY direction.
458 (cond
459 ((> left right)) ; Quit
460 (t ; Else ..
461 (let (depl square0 square1 square2 count delta)
462 (setq depl (gomoku-xy-to-index dx dy)
463 square0 (+ square (* left depl))
464 square1 (+ square (* right depl))
465 square2 (+ square0 (* 4 depl)))
466 ;; Compute the contents of the first qtuple:
467 (setq square square0
468 count 0)
469 (while (<= square square2)
470 (setq count (+ count (aref gomoku-board square))
471 square (+ square depl)))
472 (while (<= square0 square1)
473 ;; Update the squares of the qtuple beginning in SQUARE0 and ending
474 ;; in SQUARE2.
475 (setq delta (- (aref gomoku-score-trans-table count)
476 (aref gomoku-score-trans-table (- count dval))))
477 (cond ((not (zerop delta)) ; or else nothing to update
478 (setq square square0)
479 (while (<= square square2)
480 (if (zerop (aref gomoku-board square)) ; only for free squares
481 (aset gomoku-score-table square
482 (+ (aref gomoku-score-table square) delta)))
483 (setq square (+ square depl)))))
484 ;; Then shift the qtuple one square along DEPL, this only requires
485 ;; modifying SQUARE0 and SQUARE2.
486 (setq square2 (+ square2 depl)
487 count (+ count (- (aref gomoku-board square0))
488 (aref gomoku-board square2))
489 square0 (+ square0 depl)))))))
490 \f
491 ;;;
492 ;;; GAME CONTROL.
493 ;;;
494
495 ;; Several variables are used to monitor a game, including a GAME-HISTORY (the
496 ;; list of all (SQUARE . PREVSCORE) played) that allows to take moves back
497 ;; (anti-updating the score table) and to compute the table from scratch in
498 ;; case of an interruption.
499
500 (defvar gomoku-game-in-progress nil
501 "Non-nil if a game is in progress.")
502
503 (defvar gomoku-game-history nil
504 "A record of all moves that have been played during current game.")
505
506 (defvar gomoku-number-of-moves nil
507 "Number of moves already played in current game.")
508
509 (defvar gomoku-number-of-human-moves nil
510 "Number of moves already played by human in current game.")
511
512 (defvar gomoku-emacs-played-first nil
513 "Non-nil if Emacs played first.")
514
515 (defvar gomoku-human-took-back nil
516 "Non-nil if Human took back a move during the game.")
517
518 (defvar gomoku-human-refused-draw nil
519 "Non-nil if Human refused Emacs offer of a draw.")
520
521 (defvar gomoku-emacs-is-computing nil
522 ;; This is used to detect interruptions. Hopefully, it should not be needed.
523 "Non-nil if Emacs is in the middle of a computation.")
524
525
526 (defun gomoku-start-game (n m)
527 "Initialize a new game on an N by M board."
528 (setq gomoku-emacs-is-computing t) ; Raise flag
529 (setq gomoku-game-in-progress t)
530 (setq gomoku-board-width n
531 gomoku-board-height m
532 gomoku-vector-length (1+ (* (+ m 2) (1+ n)))
533 gomoku-draw-limit (/ (* 7 n m) 10))
534 (setq gomoku-game-history nil
535 gomoku-number-of-moves 0
536 gomoku-number-of-human-moves 0
537 gomoku-emacs-played-first nil
538 gomoku-human-took-back nil
539 gomoku-human-refused-draw nil)
540 (gomoku-init-display n m) ; Display first: the rest takes time
541 (gomoku-init-score-table) ; INIT-BOARD requires that the score
542 (gomoku-init-board) ; table be already created.
543 (setq gomoku-emacs-is-computing nil))
544
545 (defun gomoku-play-move (square val &optional dont-update-score)
546 "Go to SQUARE, play VAL and update everything."
547 (setq gomoku-emacs-is-computing t) ; Raise flag
548 (cond ((= 1 val) ; a Human move
549 (setq gomoku-number-of-human-moves (1+ gomoku-number-of-human-moves)))
550 ((zerop gomoku-number-of-moves) ; an Emacs move. Is it first ?
551 (setq gomoku-emacs-played-first t)))
552 (setq gomoku-game-history
553 (cons (cons square (aref gomoku-score-table square))
554 gomoku-game-history)
555 gomoku-number-of-moves (1+ gomoku-number-of-moves))
556 (gomoku-plot-square square val)
557 (aset gomoku-board square val) ; *BEFORE* UPDATE-SCORE !
558 (if dont-update-score nil
559 (gomoku-update-score-table square val) ; previous val was 0: dval = val
560 (aset gomoku-score-table square -1))
561 (setq gomoku-emacs-is-computing nil))
562
563 (defun gomoku-take-back ()
564 "Take back last move and update everything."
565 (setq gomoku-emacs-is-computing t)
566 (let* ((last-move (car gomoku-game-history))
567 (square (car last-move))
568 (oldval (aref gomoku-board square)))
569 (if (= 1 oldval)
570 (setq gomoku-number-of-human-moves (1- gomoku-number-of-human-moves)))
571 (setq gomoku-game-history (cdr gomoku-game-history)
572 gomoku-number-of-moves (1- gomoku-number-of-moves))
573 (gomoku-plot-square square 0)
574 (aset gomoku-board square 0) ; *BEFORE* UPDATE-SCORE !
575 (gomoku-update-score-table square (- oldval))
576 (aset gomoku-score-table square (cdr last-move)))
577 (setq gomoku-emacs-is-computing nil))
578 \f
579 ;;;
580 ;;; SESSION CONTROL.
581 ;;;
582
583 (defvar gomoku-number-of-emacs-wins 0
584 "Number of games Emacs won in this session.")
585
586 (defvar gomoku-number-of-human-wins 0
587 "Number of games you won in this session.")
588
589 (defvar gomoku-number-of-draws 0
590 "Number of games already drawn in this session.")
591
592
593 (defun gomoku-terminate-game (result)
594 "Terminate the current game with RESULT."
595 (let (message)
596 (cond
597 ((eq result 'emacs-won)
598 (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
599 (setq message
600 (cond ((< gomoku-number-of-moves 20)
601 "This was a REALLY QUICK win.")
602 (gomoku-human-refused-draw
603 "I won... Too bad you refused my offer of a draw !")
604 (gomoku-human-took-back
605 "I won... Taking moves back will not help you !")
606 ((not gomoku-emacs-played-first)
607 "I won... Playing first did not help you much !")
608 ((and (zerop gomoku-number-of-human-wins)
609 (zerop gomoku-number-of-draws)
610 (> gomoku-number-of-emacs-wins 1))
611 "I'm becoming tired of winning...")
612 (t
613 "I won."))))
614 ((eq result 'human-won)
615 (setq gomoku-number-of-human-wins (1+ gomoku-number-of-human-wins))
616 (setq message
617 (cond
618 (gomoku-human-took-back
619 "OK, you won this one. I, for one, never take my moves back...")
620 (gomoku-emacs-played-first
621 "OK, you won this one... so what ?")
622 (t
623 "OK, you won this one. Now, let me play first just once."))))
624 ((eq result 'human-resigned)
625 (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
626 (setq message "So you resign. That's just one more win for me."))
627 ((eq result 'nobody-won)
628 (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
629 (setq message
630 (cond
631 (gomoku-human-took-back
632 "This is a draw. I, for one, never take my moves back...")
633 (gomoku-emacs-played-first
634 "This is a draw. Just chance, I guess.")
635 (t
636 "This is a draw. Now, let me play first just once."))))
637 ((eq result 'draw-agreed)
638 (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
639 (setq message
640 (cond
641 (gomoku-human-took-back
642 "Draw agreed. I, for one, never take my moves back...")
643 (gomoku-emacs-played-first
644 "Draw agreed. You were lucky.")
645 (t
646 "Draw agreed. Now, let me play first just once."))))
647 ((eq result 'crash-game)
648 (setq message
649 "Sorry, I have been interrupted and cannot resume that game...")))
650
651 (gomoku-display-statistics)
652 (if message (message message))
653 (ding)
654 (setq gomoku-game-in-progress nil)))
655
656 (defun gomoku-crash-game ()
657 "What to do when Emacs detects it has been interrupted."
658 (setq gomoku-emacs-is-computing nil)
659 (gomoku-terminate-game 'crash-game)
660 (sit-for 4) ; Let's see the message
661 (gomoku-prompt-for-other-game))
662 \f
663 ;;;
664 ;;; INTERACTIVE COMMANDS.
665 ;;;
666
667 ;;;###autoload
668 (defun gomoku (&optional n m)
669 "Start a Gomoku game between you and Emacs.
670 If a game is in progress, this command allow you to resume it.
671 If optional arguments N and M are given, an N by M board is used.
672
673 You and Emacs play in turn by marking a free square. You mark it with X
674 and Emacs marks it with O. The winner is the first to get five contiguous
675 marks horizontally, vertically or in diagonal.
676
677 You play by moving the cursor over the square you choose and hitting
678 \\<gomoku-mode-map>\\[gomoku-human-plays].
679 Use \\[describe-mode] for more info."
680 (interactive)
681 (gomoku-switch-to-window)
682 (cond
683 (gomoku-emacs-is-computing
684 (gomoku-crash-game))
685 ((not gomoku-game-in-progress)
686 (let ((max-width (gomoku-max-width))
687 (max-height (gomoku-max-height)))
688 (or n (setq n max-width))
689 (or m (setq m max-height))
690 (cond ((< n 1)
691 (error "I need at least 1 column"))
692 ((< m 1)
693 (error "I need at least 1 row"))
694 ((> n max-width)
695 (error "I cannot display %d columns in that window" n)))
696 (if (and (> m max-height)
697 (not (equal m gomoku-saved-board-height))
698 ;; Use EQUAL because SAVED-BOARD-HEIGHT may be nil
699 (not (y-or-n-p (format "Do you really want %d rows " m))))
700 (setq m max-height)))
701 (message "One moment, please...")
702 (gomoku-start-game n m)
703 (if (y-or-n-p "Do you allow me to play first ")
704 (gomoku-emacs-plays)
705 (gomoku-prompt-for-move)))
706 ((y-or-n-p "Shall we continue our game ")
707 (gomoku-prompt-for-move))
708 (t
709 (gomoku-human-resigns))))
710
711 (defun gomoku-emacs-plays ()
712 "Compute Emacs next move and play it."
713 (interactive)
714 (gomoku-switch-to-window)
715 (cond
716 (gomoku-emacs-is-computing
717 (gomoku-crash-game))
718 ((not gomoku-game-in-progress)
719 (gomoku-prompt-for-other-game))
720 (t
721 (message "Let me think...")
722 (let (square score)
723 (setq square (gomoku-strongest-square))
724 (cond ((null square)
725 (gomoku-terminate-game 'nobody-won))
726 (t
727 (setq score (aref gomoku-score-table square))
728 (gomoku-play-move square 6)
729 (cond ((>= score gomoku-winning-threshold)
730 (gomoku-find-filled-qtuple square 6)
731 (gomoku-cross-winning-qtuple)
732 (gomoku-terminate-game 'emacs-won))
733 ((zerop score)
734 (gomoku-terminate-game 'nobody-won))
735 ((and (> gomoku-number-of-moves gomoku-draw-limit)
736 (not gomoku-human-refused-draw)
737 (gomoku-offer-a-draw))
738 (gomoku-terminate-game 'draw-agreed))
739 (t
740 (gomoku-prompt-for-move)))))))))
741
742 (defun gomoku-click (click)
743 "Play at the square where you click."
744 (interactive "e")
745 (mouse-set-point click)
746 (gomoku-human-plays))
747
748 (defun gomoku-human-plays ()
749 "Signal to the Gomoku program that you have played.
750 You must have put the cursor on the square where you want to play.
751 If the game is finished, this command requests for another game."
752 (interactive)
753 (gomoku-switch-to-window)
754 (cond
755 (gomoku-emacs-is-computing
756 (gomoku-crash-game))
757 ((not gomoku-game-in-progress)
758 (gomoku-prompt-for-other-game))
759 (t
760 (let (square score)
761 (setq square (gomoku-point-square))
762 (cond ((null square)
763 (error "Your point is not on a square. Retry !"))
764 ((not (zerop (aref gomoku-board square)))
765 (error "Your point is not on a free square. Retry !"))
766 (t
767 (setq score (aref gomoku-score-table square))
768 (gomoku-play-move square 1)
769 (cond ((and (>= score gomoku-loosing-threshold)
770 ;; Just testing SCORE > THRESHOLD is not enough for
771 ;; detecting wins, it just gives an indication that
772 ;; we confirm with GOMOKU-FIND-FILLED-QTUPLE.
773 (gomoku-find-filled-qtuple square 1))
774 (gomoku-cross-winning-qtuple)
775 (gomoku-terminate-game 'human-won))
776 (t
777 (gomoku-emacs-plays)))))))))
778
779 (defun gomoku-human-takes-back ()
780 "Signal to the Gomoku program that you wish to take back your last move."
781 (interactive)
782 (gomoku-switch-to-window)
783 (cond
784 (gomoku-emacs-is-computing
785 (gomoku-crash-game))
786 ((not gomoku-game-in-progress)
787 (message "Too late for taking back...")
788 (sit-for 4)
789 (gomoku-prompt-for-other-game))
790 ((zerop gomoku-number-of-human-moves)
791 (message "You have not played yet... Your move ?"))
792 (t
793 (message "One moment, please...")
794 ;; It is possible for the user to let Emacs play several consecutive
795 ;; moves, so that the best way to know when to stop taking back moves is
796 ;; to count the number of human moves:
797 (setq gomoku-human-took-back t)
798 (let ((number gomoku-number-of-human-moves))
799 (while (= number gomoku-number-of-human-moves)
800 (gomoku-take-back)))
801 (gomoku-prompt-for-move))))
802
803 (defun gomoku-human-resigns ()
804 "Signal to the Gomoku program that you may want to resign."
805 (interactive)
806 (gomoku-switch-to-window)
807 (cond
808 (gomoku-emacs-is-computing
809 (gomoku-crash-game))
810 ((not gomoku-game-in-progress)
811 (message "There is no game in progress"))
812 ((y-or-n-p "You mean, you resign ")
813 (gomoku-terminate-game 'human-resigned))
814 ((y-or-n-p "You mean, we continue ")
815 (gomoku-prompt-for-move))
816 (t
817 (gomoku-terminate-game 'human-resigned)))) ; OK. Accept it
818 \f
819 ;;;
820 ;;; PROMPTING THE HUMAN PLAYER.
821 ;;;
822
823 (defun gomoku-prompt-for-move ()
824 "Display a message asking for Human's move."
825 (message (if (zerop gomoku-number-of-human-moves)
826 "Your move ? (move to a free square and hit X, RET ...)"
827 "Your move ?"))
828 ;; This may seem silly, but if one omits the following line (or a similar
829 ;; one), the cursor may very well go to some place where POINT is not.
830 (save-excursion (set-buffer (other-buffer))))
831
832 (defun gomoku-prompt-for-other-game ()
833 "Ask for another game, and start it."
834 (if (y-or-n-p "Another game ")
835 (gomoku gomoku-board-width gomoku-board-height)
836 (message "Chicken !")))
837
838 (defun gomoku-offer-a-draw ()
839 "Offer a draw and return T if Human accepted it."
840 (or (y-or-n-p "I offer you a draw. Do you accept it ")
841 (prog1 (setq gomoku-human-refused-draw t)
842 nil)))
843 \f
844 ;;;
845 ;;; DISPLAYING THE BOARD.
846 ;;;
847
848 ;; You may change these values if you have a small screen or if the squares
849 ;; look rectangular, but spacings SHOULD be at least 2 (MUST BE at least 1).
850
851 (defconst gomoku-square-width 4
852 "*Horizontal spacing between squares on the Gomoku board.")
853
854 (defconst gomoku-square-height 2
855 "*Vertical spacing between squares on the Gomoku board.")
856
857 (defconst gomoku-x-offset 3
858 "*Number of columns between the Gomoku board and the side of the window.")
859
860 (defconst gomoku-y-offset 1
861 "*Number of lines between the Gomoku board and the top of the window.")
862
863
864 (defun gomoku-max-width ()
865 "Largest possible board width for the current window."
866 (1+ (/ (- (window-width (selected-window))
867 gomoku-x-offset gomoku-x-offset 1)
868 gomoku-square-width)))
869
870 (defun gomoku-max-height ()
871 "Largest possible board height for the current window."
872 (1+ (/ (- (window-height (selected-window))
873 gomoku-y-offset gomoku-y-offset 2)
874 ;; 2 instead of 1 because WINDOW-HEIGHT includes the mode line !
875 gomoku-square-height)))
876
877 (defun gomoku-point-x ()
878 "Return the board column where point is, or nil if it is not a board column."
879 (let ((col (- (current-column) gomoku-x-offset)))
880 (if (and (>= col 0)
881 (zerop (% col gomoku-square-width))
882 (<= (setq col (1+ (/ col gomoku-square-width)))
883 gomoku-board-width))
884 col)))
885
886 (defun gomoku-point-y ()
887 "Return the board row where point is, or nil if it is not a board row."
888 (let ((row (- (count-lines 1 (point)) gomoku-y-offset 1)))
889 (if (and (>= row 0)
890 (zerop (% row gomoku-square-height))
891 (<= (setq row (1+ (/ row gomoku-square-height)))
892 gomoku-board-height))
893 row)))
894
895 (defun gomoku-point-square ()
896 "Return the index of the square point is on, or nil if not on the board."
897 (let (x y)
898 (and (setq x (gomoku-point-x))
899 (setq y (gomoku-point-y))
900 (gomoku-xy-to-index x y))))
901
902 (defun gomoku-goto-square (index)
903 "Move point to square number INDEX."
904 (gomoku-goto-xy (gomoku-index-to-x index) (gomoku-index-to-y index)))
905
906 (defun gomoku-goto-xy (x y)
907 "Move point to square at X, Y coords."
908 (goto-line (+ 1 gomoku-y-offset (* gomoku-square-height (1- y))))
909 (move-to-column (+ gomoku-x-offset (* gomoku-square-width (1- x)))))
910
911 (defun gomoku-plot-square (square value)
912 "Draw 'X', 'O' or '.' on SQUARE (depending on VALUE), leave point there."
913 (gomoku-goto-square square)
914 (gomoku-put-char (cond ((= value 1) ?X)
915 ((= value 6) ?O)
916 (t ?.)))
917 (sit-for 0)) ; Display NOW
918
919 (defun gomoku-put-char (char)
920 "Draw CHAR on the Gomoku screen."
921 (let ((inhibit-read-only t))
922 (insert char)
923 (delete-char 1)
924 (backward-char 1)))
925
926 (defun gomoku-init-display (n m)
927 "Display an N by M Gomoku board."
928 (buffer-disable-undo (current-buffer))
929 (let ((inhibit-read-only t))
930 (erase-buffer)
931 (let (string1 string2 string3 string4)
932 ;; We do not use gomoku-plot-square which would be too slow for
933 ;; initializing the display. Rather we build STRING1 for lines where
934 ;; board squares are to be found, and STRING2 for empty lines. STRING1 is
935 ;; like STRING2 except for dots every DX squares. Empty lines are filled
936 ;; with spaces so that cursor moving up and down remains on the same
937 ;; column.
938 (setq string1 (concat (make-string (1- gomoku-square-width) ? ) ".")
939 string1 (apply 'concat
940 (make-list (1- n) string1))
941 string1 (concat (make-string gomoku-x-offset ? ) "." string1 "\n")
942 string2 (make-string (+ 1 gomoku-x-offset
943 (* (1- n) gomoku-square-width))
944 ? )
945 string2 (concat string2 "\n")
946 string3 (apply 'concat
947 (make-list (1- gomoku-square-height) string2))
948 string3 (concat string3 string1)
949 string3 (apply 'concat
950 (make-list (1- m) string3))
951 string4 (apply 'concat
952 (make-list gomoku-y-offset string2)))
953 (insert string4 string1 string3))
954 (gomoku-goto-xy (/ (1+ n) 2) (/ (1+ m) 2)) ; center of the board
955 (sit-for 0))) ; Display NOW
956
957 (defun gomoku-display-statistics ()
958 "Obnoxiously display some statistics about previous games in mode line."
959 ;; We store this string in the mode-line-process local variable.
960 ;; This is certainly not the cleanest way out ...
961 (setq mode-line-process
962 (cond
963 ((not (zerop gomoku-number-of-draws))
964 (format ": Won %d, lost %d, drew %d"
965 gomoku-number-of-human-wins
966 gomoku-number-of-emacs-wins
967 gomoku-number-of-draws))
968 (t
969 (format ": Won %d, lost %d"
970 gomoku-number-of-human-wins
971 gomoku-number-of-emacs-wins))))
972 (force-mode-line-update))
973
974 (defun gomoku-switch-to-window ()
975 "Find or create the Gomoku buffer, and display it."
976 (interactive)
977 (let ((buff (get-buffer "*Gomoku*")))
978 (if buff ; Buffer exists:
979 (switch-to-buffer buff) ; no problem.
980 (if gomoku-game-in-progress
981 (gomoku-crash-game)) ; buffer has been killed or something
982 (switch-to-buffer "*Gomoku*") ; Anyway, start anew.
983 (gomoku-mode))))
984 \f
985 ;;;
986 ;;; CROSSING WINNING QTUPLES.
987 ;;;
988
989 ;; When someone succeeds in filling a qtuple, we draw a line over the five
990 ;; corresponding squares. One problem is that the program does not know which
991 ;; squares ! It only knows the square where the last move has been played and
992 ;; who won. The solution is to scan the board along all four directions.
993
994 (defvar gomoku-winning-qtuple-beg nil
995 "First square of the winning qtuple.")
996
997 (defvar gomoku-winning-qtuple-end nil
998 "Last square of the winning qtuple.")
999
1000 (defvar gomoku-winning-qtuple-dx nil
1001 "Direction of the winning qtuple (along the X axis).")
1002
1003 (defvar gomoku-winning-qtuple-dy nil
1004 "Direction of the winning qtuple (along the Y axis).")
1005
1006
1007 (defun gomoku-find-filled-qtuple (square value)
1008 "Return T if SQUARE belongs to a qtuple filled with VALUEs."
1009 (or (gomoku-check-filled-qtuple square value 1 0)
1010 (gomoku-check-filled-qtuple square value 0 1)
1011 (gomoku-check-filled-qtuple square value 1 1)
1012 (gomoku-check-filled-qtuple square value -1 1)))
1013
1014 (defun gomoku-check-filled-qtuple (square value dx dy)
1015 "Return T if SQUARE belongs to a qtuple filled with VALUEs along DX, DY."
1016 ;; And record it in the WINNING-QTUPLE-... variables.
1017 (let ((a 0) (b 0)
1018 (left square) (right square)
1019 (depl (gomoku-xy-to-index dx dy))
1020 a+4)
1021 (while (and (> a -4) ; stretch tuple left
1022 (= value (aref gomoku-board (setq left (- left depl)))))
1023 (setq a (1- a)))
1024 (setq a+4 (+ a 4))
1025 (while (and (< b a+4) ; stretch tuple right
1026 (= value (aref gomoku-board (setq right (+ right depl)))))
1027 (setq b (1+ b)))
1028 (cond ((= b a+4) ; tuple length = 5 ?
1029 (setq gomoku-winning-qtuple-beg (+ square (* a depl))
1030 gomoku-winning-qtuple-end (+ square (* b depl))
1031 gomoku-winning-qtuple-dx dx
1032 gomoku-winning-qtuple-dy dy)
1033 t))))
1034
1035 (defun gomoku-cross-winning-qtuple ()
1036 "Cross winning qtuple, as found by `gomoku-find-filled-qtuple'."
1037 (gomoku-cross-qtuple gomoku-winning-qtuple-beg
1038 gomoku-winning-qtuple-end
1039 gomoku-winning-qtuple-dx
1040 gomoku-winning-qtuple-dy))
1041
1042 (defun gomoku-cross-qtuple (square1 square2 dx dy)
1043 "Cross every square between SQUARE1 and SQUARE2 in the DX, DY direction."
1044 (save-excursion ; Not moving point from last square
1045 (let ((depl (gomoku-xy-to-index dx dy)))
1046 ;; WARNING: this function assumes DEPL > 0 and SQUARE2 > SQUARE1
1047 (while (not (= square1 square2))
1048 (gomoku-goto-square square1)
1049 (setq square1 (+ square1 depl))
1050 (cond
1051 ((and (= dx 1) (= dy 0)) ; Horizontal
1052 (let ((n 1))
1053 (while (< n gomoku-square-width)
1054 (setq n (1+ n))
1055 (forward-char 1)
1056 (gomoku-put-char ?-))))
1057 ((and (= dx 0) (= dy 1)) ; Vertical
1058 (let ((n 1))
1059 (while (< n gomoku-square-height)
1060 (setq n (1+ n))
1061 (next-line 1)
1062 (gomoku-put-char ?|))))
1063 ((and (= dx -1) (= dy 1)) ; 1st Diagonal
1064 (backward-char (/ gomoku-square-width 2))
1065 (next-line (/ gomoku-square-height 2))
1066 (gomoku-put-char ?/))
1067 ((and (= dx 1) (= dy 1)) ; 2nd Diagonal
1068 (forward-char (/ gomoku-square-width 2))
1069 (next-line (/ gomoku-square-height 2))
1070 (gomoku-put-char ?\\))))))
1071 (sit-for 0)) ; Display NOW
1072 \f
1073 ;;;
1074 ;;; CURSOR MOTION.
1075 ;;;
1076 (defun gomoku-move-left ()
1077 "Move point backward one column on the Gomoku board."
1078 (interactive)
1079 (let ((x (gomoku-point-x)))
1080 (backward-char (cond ((null x) 1)
1081 ((> x 1) gomoku-square-width)
1082 (t 0)))))
1083
1084 (defun gomoku-move-right ()
1085 "Move point forward one column on the Gomoku board."
1086 (interactive)
1087 (let ((x (gomoku-point-x)))
1088 (forward-char (cond ((null x) 1)
1089 ((< x gomoku-board-width) gomoku-square-width)
1090 (t 0)))))
1091
1092 (defun gomoku-move-down ()
1093 "Move point down one row on the Gomoku board."
1094 (interactive)
1095 (let ((y (gomoku-point-y)))
1096 (next-line (cond ((null y) 1)
1097 ((< y gomoku-board-height) gomoku-square-height)
1098 (t 0)))))
1099
1100 (defun gomoku-move-up ()
1101 "Move point up one row on the Gomoku board."
1102 (interactive)
1103 (let ((y (gomoku-point-y)))
1104 (previous-line (cond ((null y) 1)
1105 ((> y 1) gomoku-square-height)
1106 (t 0)))))
1107
1108 (defun gomoku-move-ne ()
1109 "Move point North East on the Gomoku board."
1110 (interactive)
1111 (gomoku-move-up)
1112 (gomoku-move-right))
1113
1114 (defun gomoku-move-se ()
1115 "Move point South East on the Gomoku board."
1116 (interactive)
1117 (gomoku-move-down)
1118 (gomoku-move-right))
1119
1120 (defun gomoku-move-nw ()
1121 "Move point North West on the Gomoku board."
1122 (interactive)
1123 (gomoku-move-up)
1124 (gomoku-move-left))
1125
1126 (defun gomoku-move-sw ()
1127 "Move point South West on the Gomoku board."
1128 (interactive)
1129 (gomoku-move-down)
1130 (gomoku-move-left))
1131
1132 (provide 'gomoku)
1133
1134 ;;; gomoku.el ends here