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