home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / packages / gomoku.el < prev    next >
Encoding:
Text File  |  1992-06-29  |  42.5 KB  |  1,167 lines

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