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