Prefer directed to neutral quotes
[emacs.git] / lisp / obsolete / landmark.el
blob39684a781ccec67bf78bbb1743f5ff76669461fd
1 ;;; landmark.el --- Neural-network robot that learns landmarks -*- lexical-binding:t -*-
3 ;; Copyright (C) 1996-1997, 2000-2015 Free Software Foundation, Inc.
5 ;; Author: Terrence Brannon (was: <brannon@rana.usc.edu>)
6 ;; Created: December 16, 1996 - first release to usenet
7 ;; Keywords: games, neural network, adaptive search, chemotaxis
8 ;; Version: 1.0
9 ;; Obsolete-since: 25.1
11 ;; This file is part of GNU Emacs.
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 3 of the License, or
16 ;; (at your option) any later version.
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.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; *Note: This package has now moved to elpa.gnu.org.*
31 ;; To try this, just type: M-x landmark-test-run
33 ;; Landmark is a relatively non-participatory game in which a robot
34 ;; attempts to maneuver towards a tree at the center of the window
35 ;; based on unique olfactory cues from each of the 4 directions. If
36 ;; the smell of the tree increases, then the weights in the robot's
37 ;; brain are adjusted to encourage this odor-driven behavior in the
38 ;; future. If the smell of the tree decreases, the robots weights are
39 ;; adjusted to discourage a correct move.
41 ;; In laymen's terms, the search space is initially flat. The point
42 ;; of training is to "turn up the edges of the search space" so that
43 ;; the robot rolls toward the center.
45 ;; Further, do not become alarmed if the robot appears to oscillate
46 ;; back and forth between two or a few positions. This simply means
47 ;; it is currently caught in a local minimum and is doing its best to
48 ;; work its way out.
50 ;; The version of this program as described has a small problem. a
51 ;; move in a net direction can produce gross credit assignment. for
52 ;; example, if moving south will produce positive payoff, then, if in
53 ;; a single move, one moves east,west and south, then both east and
54 ;; west will be improved when they shouldn't
56 ;; Many thanks to Yuri Pryadkin <yuri@rana.usc.edu> for this
57 ;; concise problem description.
59 ;;;_* Require
60 (eval-when-compile (require 'cl-lib))
62 ;;;_* From Gomoku
64 ;;; Code:
66 (defgroup landmark nil
67 "Neural-network robot that learns landmarks."
68 :prefix "landmark-"
69 :group 'games)
71 ;;;_ + THE BOARD.
73 ;; The board is a rectangular grid. We code empty squares with 0, X's with 1
74 ;; and O's with 6. The rectangle is recorded in a one dimensional vector
75 ;; containing padding squares (coded with -1). These squares allow us to
76 ;; detect when we are trying to move out of the board. We denote a square by
77 ;; its (X,Y) coords, or by the INDEX corresponding to them in the vector. The
78 ;; leftmost topmost square has coords (1,1) and index landmark-board-width + 2.
79 ;; Similarly, vectors between squares may be given by two DX, DY coords or by
80 ;; one DEPL (the difference between indexes).
82 (defvar landmark-board-width nil
83 "Number of columns on the Landmark board.")
84 (defvar landmark-board-height nil
85 "Number of lines on the Landmark board.")
87 (defvar landmark-board nil
88 "Vector recording the actual state of the Landmark board.")
90 (defvar landmark-vector-length nil
91 "Length of landmark-board vector.")
93 (defvar landmark-draw-limit nil
94 ;; This is usually set to 70% of the number of squares.
95 "After how many moves will Emacs offer a draw?")
97 (defvar landmark-cx 0
98 "This is the x coordinate of the center of the board.")
100 (defvar landmark-cy 0
101 "This is the y coordinate of the center of the board.")
103 (defvar landmark-m 0
104 "This is the x dimension of the playing board.")
106 (defvar landmark-n 0
107 "This is the y dimension of the playing board.")
110 (defun landmark-xy-to-index (x y)
111 "Translate X, Y cartesian coords into the corresponding board index."
112 (+ (* y landmark-board-width) x y))
114 (defun landmark-index-to-x (index)
115 "Return corresponding x-coord of board INDEX."
116 (% index (1+ landmark-board-width)))
118 (defun landmark-index-to-y (index)
119 "Return corresponding y-coord of board INDEX."
120 (/ index (1+ landmark-board-width)))
122 (defun landmark-init-board ()
123 "Create the landmark-board vector and fill it with initial values."
124 (setq landmark-board (make-vector landmark-vector-length 0))
125 ;; Every square is 0 (i.e. empty) except padding squares:
126 (let ((i 0) (ii (1- landmark-vector-length)))
127 (while (<= i landmark-board-width) ; The squares in [0..width] and in
128 (aset landmark-board i -1) ; [length - width - 1..length - 1]
129 (aset landmark-board ii -1) ; are padding squares.
130 (setq i (1+ i)
131 ii (1- ii))))
132 (let ((i 0))
133 (while (< i landmark-vector-length)
134 (aset landmark-board i -1) ; and also all k*(width+1)
135 (setq i (+ i landmark-board-width 1)))))
137 ;;;_ + DISPLAYING THE BOARD.
139 ;; You may change these values if you have a small screen or if the squares
140 ;; look rectangular, but spacings SHOULD be at least 2 (MUST BE at least 1).
142 (defconst landmark-square-width 2
143 "Horizontal spacing between squares on the Landmark board.")
145 (defconst landmark-square-height 1
146 "Vertical spacing between squares on the Landmark board.")
148 (defconst landmark-x-offset 3
149 "Number of columns between the Landmark board and the side of the window.")
151 (defconst landmark-y-offset 1
152 "Number of lines between the Landmark board and the top of the window.")
155 ;;;_ + LANDMARK MODE AND KEYMAP.
157 (defcustom landmark-mode-hook nil
158 "If non-nil, its value is called on entry to Landmark mode."
159 :type 'hook
160 :group 'landmark)
162 (defvar landmark-mode-map
163 (let ((map (make-sparse-keymap)))
164 ;; Key bindings for cursor motion.
165 (define-key map "y" 'landmark-move-nw) ; y
166 (define-key map "u" 'landmark-move-ne) ; u
167 (define-key map "b" 'landmark-move-sw) ; b
168 (define-key map "n" 'landmark-move-se) ; n
169 (define-key map "h" 'backward-char) ; h
170 (define-key map "l" 'forward-char) ; l
171 (define-key map "j" 'landmark-move-down) ; j
172 (define-key map "k" 'landmark-move-up) ; k
174 (define-key map [kp-7] 'landmark-move-nw)
175 (define-key map [kp-9] 'landmark-move-ne)
176 (define-key map [kp-1] 'landmark-move-sw)
177 (define-key map [kp-3] 'landmark-move-se)
178 (define-key map [kp-4] 'backward-char)
179 (define-key map [kp-6] 'forward-char)
180 (define-key map [kp-2] 'landmark-move-down)
181 (define-key map [kp-8] 'landmark-move-up)
183 (define-key map "\C-n" 'landmark-move-down) ; C-n
184 (define-key map "\C-p" 'landmark-move-up) ; C-p
186 ;; Key bindings for entering Human moves.
187 (define-key map "X" 'landmark-human-plays) ; X
188 (define-key map "x" 'landmark-human-plays) ; x
190 (define-key map " " 'landmark-start-robot) ; SPC
191 (define-key map [down-mouse-1] 'landmark-start-robot)
192 (define-key map [drag-mouse-1] 'landmark-click)
193 (define-key map [mouse-1] 'landmark-click)
194 (define-key map [down-mouse-2] 'landmark-click)
195 (define-key map [mouse-2] 'landmark-mouse-play)
196 (define-key map [drag-mouse-2] 'landmark-mouse-play)
198 (define-key map [remap previous-line] 'landmark-move-up)
199 (define-key map [remap next-line] 'landmark-move-down)
200 (define-key map [remap beginning-of-line] 'landmark-beginning-of-line)
201 (define-key map [remap end-of-line] 'landmark-end-of-line)
202 (define-key map [remap undo] 'landmark-human-takes-back)
203 (define-key map [remap advertised-undo] 'landmark-human-takes-back)
204 map)
205 "Local keymap to use in Landmark mode.")
209 (defvar landmark-emacs-won ()
210 "For making font-lock use the winner's face for the line.")
212 (defface landmark-font-lock-face-O '((((class color)) :foreground "red")
213 (t :weight bold))
214 "Face to use for Emacs's O."
215 :version "22.1"
216 :group 'landmark)
218 (defface landmark-font-lock-face-X '((((class color)) :foreground "green")
219 (t :weight bold))
220 "Face to use for your X."
221 :version "22.1"
222 :group 'landmark)
224 (defvar landmark-font-lock-keywords
225 '(("O" . 'landmark-font-lock-face-O)
226 ("X" . 'landmark-font-lock-face-X)
227 ("[-|/\\]" 0 (if landmark-emacs-won
228 'landmark-font-lock-face-O
229 'landmark-font-lock-face-X)))
230 "Font lock rules for Landmark.")
232 ;; This one is for when they set view-read-only to t: Landmark cannot
233 ;; allow View Mode to be activated in its buffer.
234 (define-derived-mode landmark-mode special-mode "Lm"
235 "Major mode for playing Lm against Emacs.
236 You and Emacs play in turn by marking a free square. You mark it with X
237 and Emacs marks it with O. The winner is the first to get five contiguous
238 marks horizontally, vertically or in diagonal.
240 You play by moving the cursor over the square you choose and hitting \\[landmark-human-plays].
242 Other useful commands:
243 \\{landmark-mode-map}
244 Entry to this mode calls the value of `landmark-mode-hook' if that value
245 is non-nil. One interesting value is `turn-on-font-lock'."
246 (landmark-display-statistics)
247 (setq-local font-lock-defaults '(landmark-font-lock-keywords t))
248 (setq buffer-read-only t)
249 (add-hook 'post-command-hook #'landmark--intangible nil t))
252 ;;;_ + THE SCORE TABLE.
255 ;; Every (free) square has a score associated to it, recorded in the
256 ;; LANDMARK-SCORE-TABLE vector. The program always plays in the square having
257 ;; the highest score.
259 (defvar landmark-score-table nil
260 "Vector recording the actual score of the free squares.")
263 ;; The key point point about the algorithm is that, rather than considering
264 ;; the board as just a set of squares, we prefer to see it as a "space" of
265 ;; internested 5-tuples of contiguous squares (called qtuples).
267 ;; The aim of the program is to fill one qtuple with its O's while preventing
268 ;; you from filling another one with your X's. To that effect, it computes a
269 ;; score for every qtuple, with better qtuples having better scores. Of
270 ;; course, the score of a qtuple (taken in isolation) is just determined by
271 ;; its contents as a set, i.e. not considering the order of its elements. The
272 ;; highest score is given to the "OOOO" qtuples because playing in such a
273 ;; qtuple is winning the game. Just after this comes the "XXXX" qtuple because
274 ;; not playing in it is just losing the game, and so on. Note that a
275 ;; "polluted" qtuple, i.e. one containing at least one X and at least one O,
276 ;; has score zero because there is no more any point in playing in it, from
277 ;; both an attacking and a defending point of view.
279 ;; Given the score of every qtuple, the score of a given free square on the
280 ;; board is just the sum of the scores of all the qtuples to which it belongs,
281 ;; because playing in that square is playing in all its containing qtuples at
282 ;; once. And it is that function which takes into account the internesting of
283 ;; the qtuples.
285 ;; This algorithm is rather simple but anyway it gives a not so dumb level of
286 ;; play. It easily extends to "n-dimensional Landmark", where a win should not
287 ;; be obtained with as few as 5 contiguous marks: 6 or 7 (depending on n !)
288 ;; should be preferred.
291 ;; Here are the scores of the nine "non-polluted" configurations. Tuning
292 ;; these values will change (hopefully improve) the strength of the program
293 ;; and may change its style (rather aggressive here).
295 (defconst landmark-nil-score 7 "Score of an empty qtuple.")
297 (defconst landmark-score-trans-table
298 (let ((Xscore 15) ; Score of a qtuple containing one X.
299 (XXscore 400) ; Score of a qtuple containing two X's.
300 (XXXscore 1800) ; Score of a qtuple containing three X's.
301 (XXXXscore 100000) ; Score of a qtuple containing four X's.
302 (Oscore 35) ; Score of a qtuple containing one O.
303 (OOscore 800) ; Score of a qtuple containing two O's.
304 (OOOscore 15000) ; Score of a qtuple containing three O's.
305 (OOOOscore 800000)) ; Score of a qtuple containing four O's.
307 ;; These values are not just random: if, given the following situation:
309 ;; . . . . . . . O .
310 ;; . X X a . . . X .
311 ;; . . . X . . . X .
312 ;; . . . X . . . X .
313 ;; . . . . . . . b .
315 ;; you want Emacs to play in "a" and not in "b", then the parameters must
316 ;; satisfy the inequality:
318 ;; 6 * XXscore > XXXscore + XXscore
320 ;; because "a" mainly belongs to six "XX" qtuples (the others are less
321 ;; important) while "b" belongs to one "XXX" and one "XX" qtuples.
322 ;; Other conditions are required to obtain sensible moves, but the
323 ;; previous example should illustrate the point. If you manage to
324 ;; improve on these values, please send me a note. Thanks.
327 ;; As we chose values 0, 1 and 6 to denote empty, X and O squares,
328 ;; the contents of a qtuple are uniquely determined by the sum of
329 ;; its elements and we just have to set up a translation table.
330 (vector landmark-nil-score Xscore XXscore XXXscore XXXXscore 0
331 Oscore 0 0 0 0 0
332 OOscore 0 0 0 0 0
333 OOOscore 0 0 0 0 0
334 OOOOscore 0 0 0 0 0
336 "Vector associating qtuple contents to their score.")
339 ;; If you do not modify drastically the previous constants, the only way for a
340 ;; square to have a score higher than OOOOscore is to belong to a "OOOO"
341 ;; qtuple, thus to be a winning move. Similarly, the only way for a square to
342 ;; have a score between XXXXscore and OOOOscore is to belong to a "XXXX"
343 ;; qtuple. We may use these considerations to detect when a given move is
344 ;; winning or losing.
346 (defconst landmark-winning-threshold
347 (aref landmark-score-trans-table (+ 6 6 6 6)) ;; OOOOscore
348 "Threshold score beyond which an Emacs move is winning.")
350 (defconst landmark-losing-threshold
351 (aref landmark-score-trans-table (+ 1 1 1 1)) ;; XXXXscore
352 "Threshold score beyond which a human move is winning.")
355 (defun landmark-strongest-square ()
356 "Compute index of free square with highest score, or nil if none."
357 ;; We just have to loop other all squares. However there are two problems:
358 ;; 1/ The SCORE-TABLE only gives correct scores to free squares. To speed
359 ;; up future searches, we set the score of padding or occupied squares
360 ;; to -1 whenever we meet them.
361 ;; 2/ We want to choose randomly between equally good moves.
362 (let ((score-max 0)
363 (count 0) ; Number of equally good moves
364 (square (landmark-xy-to-index 1 1)) ; First square
365 (end (landmark-xy-to-index landmark-board-width landmark-board-height))
366 best-square score)
367 (while (<= square end)
368 (cond
369 ;; If score is lower (i.e. most of the time), skip to next:
370 ((< (aref landmark-score-table square) score-max))
371 ;; If score is better, beware of non free squares:
372 ((> (setq score (aref landmark-score-table square)) score-max)
373 (if (zerop (aref landmark-board square)) ; is it free ?
374 (setq count 1 ; yes: take it !
375 best-square square
376 score-max score)
377 (aset landmark-score-table square -1))) ; no: kill it !
378 ;; If score is equally good, choose randomly. But first check freedom:
379 ((not (zerop (aref landmark-board square)))
380 (aset landmark-score-table square -1))
381 ((zerop (random (setq count (1+ count))))
382 (setq best-square square
383 score-max score)))
384 (setq square (1+ square))) ; try next square
385 best-square))
387 ;;;_ - INITIALIZING THE SCORE TABLE.
389 ;; At initialization the board is empty so that every qtuple amounts for
390 ;; nil-score. Therefore, the score of any square is nil-score times the number
391 ;; of qtuples that pass through it. This number is 3 in a corner and 20 if you
392 ;; are sufficiently far from the sides. As computing the number is time
393 ;; consuming, we initialize every square with 20*nil-score and then only
394 ;; consider squares at less than 5 squares from one side. We speed this up by
395 ;; taking symmetry into account.
396 ;; Also, as it is likely that successive games will be played on a board with
397 ;; same size, it is a good idea to save the initial SCORE-TABLE configuration.
399 (defvar landmark-saved-score-table nil
400 "Recorded initial value of previous score table.")
402 (defvar landmark-saved-board-width nil
403 "Recorded value of previous board width.")
405 (defvar landmark-saved-board-height nil
406 "Recorded value of previous board height.")
409 (defun landmark-init-score-table ()
410 "Create the score table vector and fill it with initial values."
411 (if (and landmark-saved-score-table ; Has it been stored last time ?
412 (= landmark-board-width landmark-saved-board-width)
413 (= landmark-board-height landmark-saved-board-height))
414 (setq landmark-score-table (copy-sequence landmark-saved-score-table))
415 ;; No, compute it:
416 (setq landmark-score-table
417 (make-vector landmark-vector-length (* 20 landmark-nil-score)))
418 (let (i j maxi maxj maxi2 maxj2)
419 (setq maxi (/ (1+ landmark-board-width) 2)
420 maxj (/ (1+ landmark-board-height) 2)
421 maxi2 (min 4 maxi)
422 maxj2 (min 4 maxj))
423 ;; We took symmetry into account and could use it more if the board
424 ;; would have been square and not rectangular !
425 ;; In our case we deal with all (i,j) in the set [1..maxi2]*[1..maxj] U
426 ;; [maxi2+1..maxi]*[1..maxj2]. Maxi2 and maxj2 are used because the
427 ;; board may well be less than 8 by 8 !
428 (setq i 1)
429 (while (<= i maxi2)
430 (setq j 1)
431 (while (<= j maxj)
432 (landmark-init-square-score i j)
433 (setq j (1+ j)))
434 (setq i (1+ i)))
435 (while (<= i maxi)
436 (setq j 1)
437 (while (<= j maxj2)
438 (landmark-init-square-score i j)
439 (setq j (1+ j)))
440 (setq i (1+ i))))
441 (setq landmark-saved-score-table (copy-sequence landmark-score-table)
442 landmark-saved-board-width landmark-board-width
443 landmark-saved-board-height landmark-board-height)))
445 (defun landmark-nb-qtuples (i j)
446 "Return the number of qtuples containing square I,J."
447 ;; This function is complicated because we have to deal
448 ;; with ugly cases like 3 by 6 boards, but it works.
449 ;; If you have a simpler (and correct) solution, send it to me. Thanks !
450 (let ((left (min 4 (1- i)))
451 (right (min 4 (- landmark-board-width i)))
452 (up (min 4 (1- j)))
453 (down (min 4 (- landmark-board-height j))))
454 (+ -12
455 (min (max (+ left right) 3) 8)
456 (min (max (+ up down) 3) 8)
457 (min (max (+ (min left up) (min right down)) 3) 8)
458 (min (max (+ (min right up) (min left down)) 3) 8))))
460 (defun landmark-init-square-score (i j)
461 "Give initial score to square I,J and to its mirror images."
462 (let ((ii (1+ (- landmark-board-width i)))
463 (jj (1+ (- landmark-board-height j)))
464 (sc (* (landmark-nb-qtuples i j) (aref landmark-score-trans-table 0))))
465 (aset landmark-score-table (landmark-xy-to-index i j) sc)
466 (aset landmark-score-table (landmark-xy-to-index ii j) sc)
467 (aset landmark-score-table (landmark-xy-to-index i jj) sc)
468 (aset landmark-score-table (landmark-xy-to-index ii jj) sc)))
469 ;;;_ - MAINTAINING THE SCORE TABLE.
472 ;; We do not provide functions for computing the SCORE-TABLE given the
473 ;; contents of the BOARD. This would involve heavy nested loops, with time
474 ;; proportional to the size of the board. It is better to update the
475 ;; SCORE-TABLE after each move. Updating needs not modify more than 36
476 ;; squares: it is done in constant time.
478 (defun landmark-update-score-table (square dval)
479 "Update score table after SQUARE received a DVAL increment."
480 ;; The board has already been updated when this function is called.
481 ;; Updating scores is done by looking for qtuples boundaries in all four
482 ;; directions and then calling update-score-in-direction.
483 ;; Finally all squares received the right increment, and then are up to
484 ;; date, except possibly for SQUARE itself if we are taking a move back for
485 ;; its score had been set to -1 at the time.
486 (let* ((x (landmark-index-to-x square))
487 (y (landmark-index-to-y square))
488 (imin (max -4 (- 1 x)))
489 (jmin (max -4 (- 1 y)))
490 (imax (min 0 (- landmark-board-width x 4)))
491 (jmax (min 0 (- landmark-board-height y 4))))
492 (landmark-update-score-in-direction imin imax
493 square 1 0 dval)
494 (landmark-update-score-in-direction jmin jmax
495 square 0 1 dval)
496 (landmark-update-score-in-direction (max imin jmin) (min imax jmax)
497 square 1 1 dval)
498 (landmark-update-score-in-direction (max (- 1 y) -4
499 (- x landmark-board-width))
500 (min 0 (- x 5)
501 (- landmark-board-height y 4))
502 square -1 1 dval)))
504 (defun landmark-update-score-in-direction (left right square dx dy dval)
505 "Update scores for all squares in the qtuples in range.
506 That is, those between the LEFTth square and the RIGHTth after SQUARE,
507 along the DX, DY direction, considering that DVAL has been added on SQUARE."
508 ;; We always have LEFT <= 0, RIGHT <= 0 and DEPL > 0 but we may very well
509 ;; have LEFT > RIGHT, indicating that no qtuple contains SQUARE along that
510 ;; DX,DY direction.
511 (cond
512 ((> left right)) ; Quit
513 (t ; Else ..
514 (let (depl square0 square1 square2 count delta)
515 (setq depl (landmark-xy-to-index dx dy)
516 square0 (+ square (* left depl))
517 square1 (+ square (* right depl))
518 square2 (+ square0 (* 4 depl)))
519 ;; Compute the contents of the first qtuple:
520 (setq square square0
521 count 0)
522 (while (<= square square2)
523 (setq count (+ count (aref landmark-board square))
524 square (+ square depl)))
525 (while (<= square0 square1)
526 ;; Update the squares of the qtuple beginning in SQUARE0 and ending
527 ;; in SQUARE2.
528 (setq delta (- (aref landmark-score-trans-table count)
529 (aref landmark-score-trans-table (- count dval))))
530 (cond ((not (zerop delta)) ; or else nothing to update
531 (setq square square0)
532 (while (<= square square2)
533 (if (zerop (aref landmark-board square)) ; only for free squares
534 (aset landmark-score-table square
535 (+ (aref landmark-score-table square) delta)))
536 (setq square (+ square depl)))))
537 ;; Then shift the qtuple one square along DEPL, this only requires
538 ;; modifying SQUARE0 and SQUARE2.
539 (setq square2 (+ square2 depl)
540 count (+ count (- (aref landmark-board square0))
541 (aref landmark-board square2))
542 square0 (+ square0 depl)))))))
545 ;;; GAME CONTROL.
548 ;; Several variables are used to monitor a game, including a GAME-HISTORY (the
549 ;; list of all (SQUARE . PREVSCORE) played) that allows to take moves back
550 ;; (anti-updating the score table) and to compute the table from scratch in
551 ;; case of an interruption.
553 (defvar landmark-game-in-progress nil
554 "Non-nil if a game is in progress.")
556 (defvar landmark-game-history nil
557 "A record of all moves that have been played during current game.")
559 (defvar landmark-number-of-moves nil
560 "Number of moves already played in current game.")
562 (defvar landmark-number-of-human-moves nil
563 "Number of moves already played by human in current game.")
565 (defvar landmark-emacs-played-first nil
566 "Non-nil if Emacs played first.")
568 (defvar landmark-human-took-back nil
569 "Non-nil if Human took back a move during the game.")
571 (defvar landmark-human-refused-draw nil
572 "Non-nil if Human refused Emacs offer of a draw.")
574 (defvar landmark-emacs-is-computing nil
575 ;; This is used to detect interruptions. Hopefully, it should not be needed.
576 "Non-nil if Emacs is in the middle of a computation.")
579 (defun landmark-start-game (n m)
580 "Initialize a new game on an N by M board."
581 (setq landmark-emacs-is-computing t) ; Raise flag
582 (setq landmark-game-in-progress t)
583 (setq landmark-board-width n
584 landmark-board-height m
585 landmark-vector-length (1+ (* (+ m 2) (1+ n)))
586 landmark-draw-limit (/ (* 7 n m) 10))
587 (setq landmark-emacs-won nil
588 landmark-game-history nil
589 landmark-number-of-moves 0
590 landmark-number-of-human-moves 0
591 landmark-emacs-played-first nil
592 landmark-human-took-back nil
593 landmark-human-refused-draw nil)
594 (landmark-init-display n m) ; Display first: the rest takes time
595 (landmark-init-score-table) ; INIT-BOARD requires that the score
596 (landmark-init-board) ; table be already created.
597 (setq landmark-emacs-is-computing nil))
599 (defun landmark-play-move (square val &optional dont-update-score)
600 "Go to SQUARE, play VAL and update everything."
601 (setq landmark-emacs-is-computing t) ; Raise flag
602 (cond ((= 1 val) ; a Human move
603 (setq landmark-number-of-human-moves (1+ landmark-number-of-human-moves)))
604 ((zerop landmark-number-of-moves) ; an Emacs move. Is it first ?
605 (setq landmark-emacs-played-first t)))
606 (setq landmark-game-history
607 (cons (cons square (aref landmark-score-table square))
608 landmark-game-history)
609 landmark-number-of-moves (1+ landmark-number-of-moves))
610 (landmark-plot-square square val)
611 (aset landmark-board square val) ; *BEFORE* UPDATE-SCORE !
612 (if dont-update-score nil
613 (landmark-update-score-table square val) ; previous val was 0: dval = val
614 (aset landmark-score-table square -1))
615 (setq landmark-emacs-is-computing nil))
617 (defun landmark-take-back ()
618 "Take back last move and update everything."
619 (setq landmark-emacs-is-computing t)
620 (let* ((last-move (car landmark-game-history))
621 (square (car last-move))
622 (oldval (aref landmark-board square)))
623 (if (= 1 oldval)
624 (setq landmark-number-of-human-moves (1- landmark-number-of-human-moves)))
625 (setq landmark-game-history (cdr landmark-game-history)
626 landmark-number-of-moves (1- landmark-number-of-moves))
627 (landmark-plot-square square 0)
628 (aset landmark-board square 0) ; *BEFORE* UPDATE-SCORE !
629 (landmark-update-score-table square (- oldval))
630 (aset landmark-score-table square (cdr last-move)))
631 (setq landmark-emacs-is-computing nil))
634 ;;;_ + SESSION CONTROL.
636 (defvar landmark-number-of-trials 0
637 "The number of times that landmark has been run.")
639 (defvar landmark-sum-of-moves 0
640 "The total number of moves made in all games.")
642 (defvar landmark-number-of-emacs-wins 0
643 "Number of games Emacs won in this session.")
645 (defvar landmark-number-of-human-wins 0
646 "Number of games you won in this session.")
648 (defvar landmark-number-of-draws 0
649 "Number of games already drawn in this session.")
652 (defun landmark-terminate-game (result)
653 "Terminate the current game with RESULT."
654 (setq landmark-number-of-trials (1+ landmark-number-of-trials))
655 (setq landmark-sum-of-moves (+ landmark-sum-of-moves landmark-number-of-moves))
656 (if (eq result 'crash-game)
657 (message
658 "Sorry, I have been interrupted and cannot resume that game..."))
659 (landmark-display-statistics)
660 ;;(ding)
661 (setq landmark-game-in-progress nil))
663 (defun landmark-crash-game ()
664 "What to do when Emacs detects it has been interrupted."
665 (setq landmark-emacs-is-computing nil)
666 (landmark-terminate-game 'crash-game)
667 (sit-for 4) ; Let's see the message
668 (landmark-prompt-for-other-game))
671 ;;;_ + INTERACTIVE COMMANDS.
673 (defun landmark-emacs-plays ()
674 "Compute Emacs next move and play it."
675 (interactive)
676 (landmark-switch-to-window)
677 (cond
678 (landmark-emacs-is-computing
679 (landmark-crash-game))
680 ((not landmark-game-in-progress)
681 (landmark-prompt-for-other-game))
683 (message "Let me think...")
684 (let ((square (landmark-strongest-square))
685 score)
686 (cond ((null square)
687 (landmark-terminate-game 'nobody-won))
689 (setq score (aref landmark-score-table square))
690 (landmark-play-move square 6)
691 (cond ((>= score landmark-winning-threshold)
692 (setq landmark-emacs-won t) ; for font-lock
693 (landmark-find-filled-qtuple square 6)
694 (landmark-terminate-game 'emacs-won))
695 ((zerop score)
696 (landmark-terminate-game 'nobody-won))
697 ((and (> landmark-number-of-moves landmark-draw-limit)
698 (not landmark-human-refused-draw)
699 (landmark-offer-a-draw))
700 (landmark-terminate-game 'draw-agreed))
702 (landmark-prompt-for-move)))))))))
704 ;; For small square dimensions this is approximate, since though measured in
705 ;; pixels, event's (X . Y) is a character's top-left corner.
706 (defun landmark-click (click)
707 "Position at the square where you click."
708 (interactive "e")
709 (and (windowp (posn-window (setq click (event-end click))))
710 (numberp (posn-point click))
711 (select-window (posn-window click))
712 (setq click (posn-col-row click))
713 (landmark-goto-xy
714 (min (max (/ (+ (- (car click)
715 landmark-x-offset
717 (window-hscroll)
718 landmark-square-width
719 (% landmark-square-width 2)
720 (/ landmark-square-width 2))
721 landmark-square-width)
723 landmark-board-width)
724 (min (max (/ (+ (- (cdr click)
725 landmark-y-offset
727 (count-lines (point-min) (window-start))
728 landmark-square-height
729 (% landmark-square-height 2)
730 (/ landmark-square-height 2))
731 landmark-square-height)
733 landmark-board-height))))
735 (defun landmark-mouse-play (click)
736 "Play at the square where you click."
737 (interactive "e")
738 (if (landmark-click click)
739 (landmark-human-plays)))
741 (defun landmark-human-plays ()
742 "Signal to the Landmark program that you have played.
743 You must have put the cursor on the square where you want to play.
744 If the game is finished, this command requests for another game."
745 (interactive)
746 (landmark-switch-to-window)
747 (cond
748 (landmark-emacs-is-computing
749 (landmark-crash-game))
750 ((not landmark-game-in-progress)
751 (landmark-prompt-for-other-game))
753 (let ((square (landmark-point-square))
754 score)
755 (cond ((null square)
756 (error "Your point is not on a square. Retry!"))
757 ((not (zerop (aref landmark-board square)))
758 (error "Your point is not on a free square. Retry!"))
760 (setq score (aref landmark-score-table square))
761 (landmark-play-move square 1)
762 (cond ((and (>= score landmark-losing-threshold)
763 ;; Just testing SCORE > THRESHOLD is not enough for
764 ;; detecting wins, it just gives an indication that
765 ;; we confirm with LANDMARK-FIND-FILLED-QTUPLE.
766 (landmark-find-filled-qtuple square 1))
767 (landmark-terminate-game 'human-won))
769 (landmark-emacs-plays)))))))))
771 (defun landmark-human-takes-back ()
772 "Signal to the Landmark program that you wish to take back your last move."
773 (interactive)
774 (landmark-switch-to-window)
775 (cond
776 (landmark-emacs-is-computing
777 (landmark-crash-game))
778 ((not landmark-game-in-progress)
779 (message "Too late for taking back...")
780 (sit-for 4)
781 (landmark-prompt-for-other-game))
782 ((zerop landmark-number-of-human-moves)
783 (message "You have not played yet... Your move?"))
785 (message "One moment, please...")
786 ;; It is possible for the user to let Emacs play several consecutive
787 ;; moves, so that the best way to know when to stop taking back moves is
788 ;; to count the number of human moves:
789 (setq landmark-human-took-back t)
790 (let ((number landmark-number-of-human-moves))
791 (while (= number landmark-number-of-human-moves)
792 (landmark-take-back)))
793 (landmark-prompt-for-move))))
795 (defun landmark-human-resigns ()
796 "Signal to the Landmark program that you may want to resign."
797 (interactive)
798 (landmark-switch-to-window)
799 (cond
800 (landmark-emacs-is-computing
801 (landmark-crash-game))
802 ((not landmark-game-in-progress)
803 (message "There is no game in progress"))
804 ((y-or-n-p "You mean, you resign? ")
805 (landmark-terminate-game 'human-resigned))
806 ((y-or-n-p "You mean, we continue? ")
807 (landmark-prompt-for-move))
809 (landmark-terminate-game 'human-resigned)))) ; OK. Accept it
811 ;;;_ + PROMPTING THE HUMAN PLAYER.
813 (defun landmark-prompt-for-move ()
814 "Display a message asking for Human's move."
815 (message (if (zerop landmark-number-of-human-moves)
816 "Your move? (move to a free square and hit X, RET ...)"
817 "Your move?")))
819 (defun landmark-prompt-for-other-game ()
820 "Ask for another game, and start it."
821 (if (y-or-n-p "Another game? ")
822 (if (y-or-n-p "Retain learned weights ")
823 (landmark 2)
824 (landmark 1))
825 (message "Chicken!")))
827 (defun landmark-offer-a-draw ()
828 "Offer a draw and return t if Human accepted it."
829 (or (y-or-n-p "I offer you a draw. Do you accept it? ")
830 (not (setq landmark-human-refused-draw t))))
833 (defun landmark-max-width ()
834 "Largest possible board width for the current window."
835 (1+ (/ (- (window-width)
836 landmark-x-offset landmark-x-offset 1)
837 landmark-square-width)))
839 (defun landmark-max-height ()
840 "Largest possible board height for the current window."
841 (1+ (/ (- (window-height)
842 landmark-y-offset landmark-y-offset 2)
843 ;; 2 instead of 1 because WINDOW-HEIGHT includes the mode line !
844 landmark-square-height)))
846 (defun landmark-point-y ()
847 "Return the board row where point is."
848 (1+ (/ (- (count-lines (point-min) (point))
849 landmark-y-offset (if (bolp) 0 1))
850 landmark-square-height)))
852 (defun landmark-point-square ()
853 "Return the index of the square point is on."
854 (landmark-xy-to-index (1+ (/ (- (current-column) landmark-x-offset)
855 landmark-square-width))
856 (landmark-point-y)))
858 (defun landmark-goto-square (index)
859 "Move point to square number INDEX."
860 (landmark-goto-xy (landmark-index-to-x index) (landmark-index-to-y index)))
862 (defun landmark-goto-xy (x y)
863 "Move point to square at X, Y coords."
864 (goto-char (point-min))
865 (forward-line (+ landmark-y-offset (* landmark-square-height (1- y))))
866 (move-to-column (+ landmark-x-offset (* landmark-square-width (1- x)))))
868 (defun landmark-plot-square (square value)
869 "Draw ‘X’, ‘O’ or ‘.’ on SQUARE depending on VALUE, leave point there."
870 (or (= value 1)
871 (landmark-goto-square square))
872 (let ((inhibit-read-only t))
873 (insert (cond ((= value 1) ?.)
874 ((= value 2) ?N)
875 ((= value 3) ?S)
876 ((= value 4) ?E)
877 ((= value 5) ?W)
878 ((= value 6) ?^)))
880 (and (zerop value)
881 (add-text-properties (1- (point)) (point)
882 '(mouse-face highlight
883 help-echo "\
884 mouse-1: get robot moving, mouse-2: play on this square")))
885 (delete-char 1)
886 (backward-char 1))
887 (sit-for 0)) ; Display NOW
889 (defun landmark-init-display (n m)
890 "Display an N by M Landmark board."
891 (buffer-disable-undo (current-buffer))
892 (let ((inhibit-read-only t)
893 (point (point-min)) opoint
894 (i m) j x)
895 ;; Try to minimize number of chars (because of text properties)
896 (setq tab-width
897 (if (zerop (% landmark-x-offset landmark-square-width))
898 landmark-square-width
899 (max (/ (+ (% landmark-x-offset landmark-square-width)
900 landmark-square-width 1) 2) 2)))
901 (erase-buffer)
902 (insert-char ?\n landmark-y-offset)
903 (while (progn
904 (setq j n
905 x (- landmark-x-offset landmark-square-width))
906 (while (>= (setq j (1- j)) 0)
907 (insert-char ?\t (/ (- (setq x (+ x landmark-square-width))
908 (current-column))
909 tab-width))
910 (insert-char ?\s (- x (current-column)))
911 (and (zerop j)
912 (= i (- m 2))
913 (progn
914 (while (>= i 3)
915 (append-to-buffer (current-buffer) opoint (point))
916 (setq i (- i 2)))
917 (goto-char (point-max))))
918 (setq point (point))
919 (insert ?=)
920 (add-text-properties point (point)
921 '(mouse-face highlight help-echo "\
922 mouse-1: get robot moving, mouse-2: play on this square")))
923 (> (setq i (1- i)) 0))
924 (if (= i (1- m))
925 (setq opoint point))
926 (insert-char ?\n landmark-square-height))
927 (insert-char ?\n))
928 (landmark-goto-xy (/ (1+ n) 2) (/ (1+ m) 2)) ; center of the board
929 (sit-for 0)) ; Display NOW
931 (defun landmark-display-statistics ()
932 "Obnoxiously display some statistics about previous games in mode line."
933 ;; We store this string in the mode-line-process local variable.
934 ;; This is certainly not the cleanest way out ...
935 (setq mode-line-process
936 (format ": Trials: %d, Avg#Moves: %d"
937 landmark-number-of-trials
938 (if (zerop landmark-number-of-trials)
940 (/ landmark-sum-of-moves landmark-number-of-trials))))
941 (force-mode-line-update))
943 (defun landmark-switch-to-window ()
944 "Find or create the Landmark buffer, and display it."
945 (interactive)
946 (let ((buff (get-buffer "*Landmark*")))
947 (if buff ; Buffer exists:
948 (switch-to-buffer buff) ; no problem.
949 (if landmark-game-in-progress
950 (landmark-crash-game)) ; buffer has been killed or something
951 (switch-to-buffer "*Landmark*") ; Anyway, start anew.
952 (landmark-mode))))
955 ;;;_ + CROSSING WINNING QTUPLES.
957 ;; When someone succeeds in filling a qtuple, we draw a line over the five
958 ;; corresponding squares. One problem is that the program does not know which
959 ;; squares ! It only knows the square where the last move has been played and
960 ;; who won. The solution is to scan the board along all four directions.
962 (defun landmark-find-filled-qtuple (square value)
963 "Return t if SQUARE belongs to a qtuple filled with VALUEs."
964 (or (landmark-check-filled-qtuple square value 1 0)
965 (landmark-check-filled-qtuple square value 0 1)
966 (landmark-check-filled-qtuple square value 1 1)
967 (landmark-check-filled-qtuple square value -1 1)))
969 (defun landmark-check-filled-qtuple (square value dx dy)
970 "Return t if SQUARE belongs to a qtuple filled with VALUEs along DX, DY."
971 (let ((a 0) (b 0)
972 (left square) (right square)
973 (depl (landmark-xy-to-index dx dy)))
974 (while (and (> a -4) ; stretch tuple left
975 (= value (aref landmark-board (setq left (- left depl)))))
976 (setq a (1- a)))
977 (while (and (< b (+ a 4)) ; stretch tuple right
978 (= value (aref landmark-board (setq right (+ right depl)))))
979 (setq b (1+ b)))
980 (cond ((= b (+ a 4)) ; tuple length = 5 ?
981 (landmark-cross-qtuple (+ square (* a depl)) (+ square (* b depl))
982 dx dy)
983 t))))
985 (defun landmark-cross-qtuple (square1 square2 dx dy)
986 "Cross every square between SQUARE1 and SQUARE2 in the DX, DY direction."
987 (save-excursion ; Not moving point from last square
988 (let ((depl (landmark-xy-to-index dx dy))
989 (inhibit-read-only t))
990 ;; WARNING: this function assumes DEPL > 0 and SQUARE2 > SQUARE1
991 (while (/= square1 square2)
992 (landmark-goto-square square1)
993 (setq square1 (+ square1 depl))
994 (cond
995 ((= dy 0) ; Horizontal
996 (forward-char 1)
997 (insert-char ?- (1- landmark-square-width) t)
998 (delete-region (point) (progn
999 (skip-chars-forward " \t")
1000 (point))))
1001 ((= dx 0) ; Vertical
1002 (let ((landmark-n 1)
1003 (column (current-column)))
1004 (while (< landmark-n landmark-square-height)
1005 (setq landmark-n (1+ landmark-n))
1006 (forward-line 1)
1007 (indent-to column)
1008 (insert ?|))))
1009 ((= dx -1) ; 1st Diagonal
1010 (indent-to (prog1 (- (current-column) (/ landmark-square-width 2))
1011 (forward-line (/ landmark-square-height 2))))
1012 (insert ?/))
1013 (t ; 2nd Diagonal
1014 (indent-to (prog1 (+ (current-column) (/ landmark-square-width 2))
1015 (forward-line (/ landmark-square-height 2))))
1016 (insert ?\\))))))
1017 (sit-for 0)) ; Display NOW
1020 ;;;_ + CURSOR MOTION.
1022 (defvar-local landmark--last-pos 0)
1024 (defconst landmark--intangible-chars "- \t\n|/\\\\")
1026 (defun landmark--intangible ()
1027 (when (or (eobp)
1028 (save-excursion
1029 (not (zerop (skip-chars-forward landmark--intangible-chars)))))
1030 (if (<= landmark--last-pos (point)) ;Moving forward.
1031 (progn
1032 (skip-chars-forward landmark--intangible-chars)
1033 (when (eobp)
1034 (skip-chars-backward landmark--intangible-chars)
1035 (forward-char -1)))
1036 (skip-chars-backward landmark--intangible-chars)
1037 (if (bobp)
1038 (skip-chars-forward landmark--intangible-chars)
1039 (forward-char -1))))
1040 (setq landmark--last-pos (point)))
1042 ;; previous-line and next-line don't work right with intangible newlines
1043 (defun landmark-move-down ()
1044 "Move point down one row on the Landmark board."
1045 (interactive)
1046 (if (< (landmark-point-y) landmark-board-height)
1047 (let ((col (current-column)))
1048 (forward-line 1) ;;; landmark-square-height
1049 (move-to-column col))))
1051 (defun landmark-move-up ()
1052 "Move point up one row on the Landmark board."
1053 (interactive)
1054 (if (> (landmark-point-y) 1)
1055 (let ((col (current-column)))
1056 (forward-line (- landmark-square-height))
1057 (move-to-column col))))
1059 (defun landmark-move-ne ()
1060 "Move point North East on the Landmark board."
1061 (interactive)
1062 (landmark-move-up)
1063 (forward-char))
1065 (defun landmark-move-se ()
1066 "Move point South East on the Landmark board."
1067 (interactive)
1068 (landmark-move-down)
1069 (forward-char))
1071 (defun landmark-move-nw ()
1072 "Move point North West on the Landmark board."
1073 (interactive)
1074 (landmark-move-up)
1075 (backward-char))
1077 (defun landmark-move-sw ()
1078 "Move point South West on the Landmark board."
1079 (interactive)
1080 (landmark-move-down)
1081 (backward-char))
1083 (defun landmark-beginning-of-line ()
1084 "Move point to first square on the Landmark board row."
1085 (interactive)
1086 (move-to-column landmark-x-offset))
1088 (defun landmark-end-of-line ()
1089 "Move point to last square on the Landmark board row."
1090 (interactive)
1091 (move-to-column (+ landmark-x-offset
1092 (* landmark-square-width (1- landmark-board-width)))))
1095 ;;;_ + Simulation variables
1097 ;;;_ - landmark-nvar
1098 (defvar landmark-nvar 0.0075
1099 "Not used.
1100 Affects a noise generator which was used in an earlier incarnation of
1101 this program to add a random element to the way moves were made.")
1102 ;;;_ - lists of cardinal directions
1103 ;;;_ :
1104 (defvar landmark-ns '(landmark-n landmark-s)
1105 "Used when doing something relative to the north and south axes.")
1106 (defvar landmark-ew '(landmark-e landmark-w)
1107 "Used when doing something relative to the east and west axes.")
1108 (defvar landmark-directions '(landmark-n landmark-s landmark-e landmark-w)
1109 "The cardinal directions.")
1110 (defvar landmark-8-directions
1111 '((landmark-n) (landmark-n landmark-w) (landmark-w) (landmark-s landmark-w)
1112 (landmark-s) (landmark-s landmark-e) (landmark-e) (landmark-n landmark-e))
1113 "The full 8 possible directions.")
1115 (defvar landmark-number-of-moves
1116 "The number of moves made by the robot so far.")
1119 ;;;_* Terry's mods to create lm.el
1121 ;;;(setq landmark-debug nil)
1122 (defvar landmark-debug nil
1123 "If non-nil, debugging is printed.")
1124 (defcustom landmark-one-moment-please nil
1125 "If non-nil, print \"One moment please\" when a new board is generated.
1126 The drawback of this is you don't see how many moves the last run took
1127 because it is overwritten by \"One moment please\"."
1128 :type 'boolean
1129 :group 'landmark)
1130 (defcustom landmark-output-moves t
1131 "If non-nil, output number of moves so far on a move-by-move basis."
1132 :type 'boolean
1133 :group 'landmark)
1136 (defun landmark-weights-debug ()
1137 (if landmark-debug
1138 (progn (landmark-print-wts) (landmark-blackbox) (landmark-print-y-s-noise)
1139 (landmark-print-smell))))
1141 ;;;_ - Printing various things
1142 (defun landmark-print-distance-int (direction)
1143 (interactive)
1144 (insert (format "%S %S " direction (get direction 'distance))))
1147 (defun landmark-print-distance ()
1148 (insert (format "tree: %S \n" (landmark-calc-distance-of-robot-from 'landmark-tree)))
1149 (mapc 'landmark-print-distance-int landmark-directions))
1152 ;;(setq direction 'landmark-n)
1153 ;;(get 'landmark-n 'landmark-s)
1154 (defun landmark-nslify-wts-int (direction)
1155 (mapcar (lambda (target-direction)
1156 (get direction target-direction))
1157 landmark-directions))
1160 (defun landmark-nslify-wts ()
1161 (interactive)
1162 (let ((l (apply 'append (mapcar 'landmark-nslify-wts-int landmark-directions))))
1163 (insert (format "set data_value WTS \n %s \n" l))
1164 (insert (format "/* max: %S min: %S */"
1165 (eval (cons 'max l)) (eval (cons 'min l))))))
1167 (defun landmark-print-wts-int (direction)
1168 (mapc (lambda (target-direction)
1169 (insert (format "%S %S %S "
1170 direction
1171 target-direction
1172 (get direction target-direction))))
1173 landmark-directions)
1174 (insert "\n"))
1176 (defun landmark-print-wts ()
1177 (interactive)
1178 (with-current-buffer "*landmark-wts*"
1179 (insert "==============================\n")
1180 (mapc 'landmark-print-wts-int landmark-directions)))
1182 (defun landmark-print-moves (moves)
1183 (interactive)
1184 (with-current-buffer "*landmark-moves*"
1185 (insert (format "%S\n" moves))))
1188 (defun landmark-print-y-s-noise-int (direction)
1189 (insert (format "%S:landmark-y %S, s %S, noise %S \n"
1190 (symbol-name direction)
1191 (get direction 'y_t)
1192 (get direction 's)
1193 (get direction 'noise)
1196 (defun landmark-print-y-s-noise ()
1197 (interactive)
1198 (with-current-buffer "*landmark-y,s,noise*"
1199 (insert "==============================\n")
1200 (mapc 'landmark-print-y-s-noise-int landmark-directions)))
1202 (defun landmark-print-smell-int (direction)
1203 (insert (format "%S: smell: %S \n"
1204 (symbol-name direction)
1205 (get direction 'smell))))
1207 (defun landmark-print-smell ()
1208 (interactive)
1209 (with-current-buffer "*landmark-smell*"
1210 (insert "==============================\n")
1211 (insert (format "tree: %S \n" (get 'z 't)))
1212 (mapc 'landmark-print-smell-int landmark-directions)))
1214 (defun landmark-print-w0-int (direction)
1215 (insert (format "%S: w0: %S \n"
1216 (symbol-name direction)
1217 (get direction 'w0))))
1219 (defun landmark-print-w0 ()
1220 (interactive)
1221 (with-current-buffer "*landmark-w0*"
1222 (insert "==============================\n")
1223 (mapc 'landmark-print-w0-int landmark-directions)))
1225 (defun landmark-blackbox ()
1226 (with-current-buffer "*landmark-blackbox*"
1227 (insert "==============================\n")
1228 (insert "I smell: ")
1229 (mapc (lambda (direction)
1230 (if (> (get direction 'smell) 0)
1231 (insert (format "%S " direction))))
1232 landmark-directions)
1233 (insert "\n")
1235 (insert "I move: ")
1236 (mapc (lambda (direction)
1237 (if (> (get direction 'y_t) 0)
1238 (insert (format "%S " direction))))
1239 landmark-directions)
1240 (insert "\n")
1241 (landmark-print-wts-blackbox)
1242 (insert (format "z_t-z_t-1: %S" (- (get 'z 't) (get 'z 't-1))))
1243 (landmark-print-distance)
1244 (insert "\n")))
1246 (defun landmark-print-wts-blackbox ()
1247 (interactive)
1248 (mapc 'landmark-print-wts-int landmark-directions))
1250 ;;;_ - learning parameters
1251 (defcustom landmark-bound 0.005
1252 "The maximum that w0j may be."
1253 :type 'number
1254 :group 'landmark)
1255 (defcustom landmark-c 1.0
1256 "A factor applied to modulate the increase in wij.
1257 Used in the function landmark-update-normal-weights."
1258 :type 'number
1259 :group 'landmark)
1260 (defcustom landmark-c-naught 0.5
1261 "A factor applied to modulate the increase in w0j.
1262 Used in the function landmark-update-naught-weights."
1263 :type 'number
1264 :group 'landmark)
1265 (defvar landmark-initial-w0 0.0)
1266 (defvar landmark-initial-wij 0.0)
1267 (defcustom landmark-no-payoff 0
1268 "The amount of simulation cycles that have occurred with no movement.
1269 Used to move the robot when he is stuck in a rut for some reason."
1270 :type 'integer
1271 :group 'landmark)
1272 (defcustom landmark-max-stall-time 2
1273 "The maximum number of cycles that the robot can remain stuck in a place.
1274 After this limit is reached, landmark-random-move is called to push him out of it."
1275 :type 'integer
1276 :group 'landmark)
1279 ;;;_ + Randomizing functions
1280 ;;;_ - landmark-flip-a-coin ()
1281 (defun landmark-flip-a-coin ()
1282 (if (> (random 5000) 2500)
1285 ;;;_ : landmark-very-small-random-number ()
1286 ;(defun landmark-very-small-random-number ()
1287 ; (/
1288 ; (* (/ (random 900000) 900000.0) .0001)))
1289 ;;;_ : landmark-randomize-weights-for (direction)
1290 (defun landmark-randomize-weights-for (direction)
1291 (mapc (lambda (target-direction)
1292 (put direction
1293 target-direction
1294 (* (landmark-flip-a-coin) (/ (random 10000) 10000.0))))
1295 landmark-directions))
1296 ;;;_ : landmark-noise ()
1297 (defun landmark-noise ()
1298 (* (- (/ (random 30001) 15000.0) 1) landmark-nvar))
1300 ;;;_ : landmark-fix-weights-for (direction)
1301 (defun landmark-fix-weights-for (direction)
1302 (mapc (lambda (target-direction)
1303 (put direction
1304 target-direction
1305 landmark-initial-wij))
1306 landmark-directions))
1309 ;;;_ + Plotting functions
1310 ;;;_ - landmark-plot-internal (sym)
1311 (defun landmark-plot-internal (sym)
1312 (landmark-plot-square (landmark-xy-to-index
1313 (get sym 'x)
1314 (get sym 'y))
1315 (get sym 'sym)))
1316 ;;;_ - landmark-plot-landmarks ()
1317 (defun landmark-plot-landmarks ()
1318 (setq landmark-cx (/ landmark-board-width 2))
1319 (setq landmark-cy (/ landmark-board-height 2))
1321 (put 'landmark-n 'x landmark-cx)
1322 (put 'landmark-n 'y 1)
1323 (put 'landmark-n 'sym 2)
1325 (put 'landmark-tree 'x landmark-cx)
1326 (put 'landmark-tree 'y landmark-cy)
1327 (put 'landmark-tree 'sym 6)
1329 (put 'landmark-s 'x landmark-cx)
1330 (put 'landmark-s 'y landmark-board-height)
1331 (put 'landmark-s 'sym 3)
1333 (put 'landmark-w 'x 1)
1334 (put 'landmark-w 'y (/ landmark-board-height 2))
1335 (put 'landmark-w 'sym 5)
1337 (put 'landmark-e 'x landmark-board-width)
1338 (put 'landmark-e 'y (/ landmark-board-height 2))
1339 (put 'landmark-e 'sym 4)
1341 (mapc 'landmark-plot-internal '(landmark-n landmark-s landmark-e landmark-w landmark-tree)))
1345 ;;;_ + Distance-calculation functions
1347 ;;;_ - distance (x x0 y y0)
1348 (defun landmark--distance (x x0 y y0)
1349 (let ((dx (- x x0)) (dy (- y y0)))
1350 (sqrt (+ (* dx dx) (* dy dy)))))
1352 ;;;_ - landmark-calc-distance-of-robot-from (direction)
1353 (defun landmark-calc-distance-of-robot-from (direction)
1354 (put direction 'distance
1355 (landmark--distance (get direction 'x)
1356 (landmark-index-to-x (landmark-point-square))
1357 (get direction 'y)
1358 (landmark-index-to-y (landmark-point-square)))))
1360 ;;;_ - landmark-calc-smell-internal (sym)
1361 (defun landmark-calc-smell-internal (sym)
1362 (let ((r (get sym 'r))
1363 (d (landmark-calc-distance-of-robot-from sym)))
1364 (if (> (* 0.5 (- 1 (/ d r))) 0)
1365 (* 0.5 (- 1 (/ d r)))
1366 0)))
1369 ;;;_ + Learning (neural) functions
1370 (defun landmark-f (x)
1371 (cond
1372 ((> x landmark-bound) landmark-bound)
1373 ((< x 0.0) 0.0)
1374 (t x)))
1376 (defun landmark-y (direction)
1377 (put direction 'noise (landmark-noise))
1378 (put direction 'y_t
1379 (if (> (get direction 's) 0.0)
1381 0.0)))
1383 (defun landmark-update-normal-weights (direction)
1384 (mapc (lambda (target-direction)
1385 (put direction target-direction
1387 (get direction target-direction)
1388 (* landmark-c
1389 (- (get 'z 't) (get 'z 't-1))
1390 (get target-direction 'y_t)
1391 (get direction 'smell)))))
1392 landmark-directions))
1394 (defun landmark-update-naught-weights (direction)
1395 (mapc (lambda (_target-direction)
1396 (put direction 'w0
1397 (landmark-f
1399 (get direction 'w0)
1400 (* landmark-c-naught
1401 (- (get 'z 't) (get 'z 't-1))
1402 (get direction 'y_t))))))
1403 landmark-directions))
1406 ;;;_ + Statistics gathering and creating functions
1408 (defun landmark-calc-current-smells ()
1409 (mapc (lambda (direction)
1410 (put direction 'smell (landmark-calc-smell-internal direction)))
1411 landmark-directions))
1413 (defun landmark-calc-payoff ()
1414 (put 'z 't-1 (get 'z 't))
1415 (put 'z 't (landmark-calc-smell-internal 'landmark-tree))
1416 (if (= (- (get 'z 't) (get 'z 't-1)) 0.0)
1417 (cl-incf landmark-no-payoff)
1418 (setf landmark-no-payoff 0)))
1420 (defun landmark-store-old-y_t ()
1421 (mapc (lambda (direction)
1422 (put direction 'y_t-1 (get direction 'y_t)))
1423 landmark-directions))
1426 ;;;_ + Functions to move robot
1428 (defun landmark-confidence-for (target-direction)
1429 (apply '+
1430 (get target-direction 'w0)
1431 (mapcar (lambda (direction)
1433 (get direction target-direction)
1434 (get direction 'smell)))
1435 landmark-directions)))
1438 (defun landmark-calc-confidences ()
1439 (mapc (lambda (direction)
1440 (put direction 's (landmark-confidence-for direction)))
1441 landmark-directions))
1443 (defun landmark-move ()
1444 (if (and (= (get 'landmark-n 'y_t) 1.0) (= (get 'landmark-s 'y_t) 1.0))
1445 (progn
1446 (mapc (lambda (dir) (put dir 'y_t 0)) landmark-ns)
1447 (if landmark-debug
1448 (message "n-s normalization."))))
1449 (if (and (= (get 'landmark-w 'y_t) 1.0) (= (get 'landmark-e 'y_t) 1.0))
1450 (progn
1451 (mapc (lambda (dir) (put dir 'y_t 0)) landmark-ew)
1452 (if landmark-debug
1453 (message "e-w normalization"))))
1455 (mapc (lambda (pair)
1456 (when (> (get (car pair) 'y_t) 0)
1457 (funcall (car (cdr pair)))
1458 (landmark--intangible)))
1460 (landmark-n landmark-move-up)
1461 (landmark-s landmark-move-down)
1462 (landmark-e forward-char)
1463 (landmark-w backward-char)))
1464 (landmark-plot-square (landmark-point-square) 1)
1465 (cl-incf landmark-number-of-moves)
1466 (if landmark-output-moves
1467 (message "Moves made: %d" landmark-number-of-moves)))
1470 (defun landmark-random-move ()
1471 (mapc
1472 (lambda (direction) (put direction 'y_t 0))
1473 landmark-directions)
1474 (dolist (direction (nth (random 8) landmark-8-directions))
1475 (put direction 'y_t 1.0))
1476 (landmark-move))
1478 (defun landmark-amble-robot ()
1479 (interactive)
1480 (while (> (landmark-calc-distance-of-robot-from 'landmark-tree) 0)
1482 (landmark-store-old-y_t)
1483 (landmark-calc-current-smells)
1485 (if (> landmark-no-payoff landmark-max-stall-time)
1486 (landmark-random-move)
1487 (progn
1488 (landmark-calc-confidences)
1489 (mapc 'landmark-y landmark-directions)
1490 (landmark-move)))
1492 (landmark-calc-payoff)
1494 (mapc 'landmark-update-normal-weights landmark-directions)
1495 (mapc 'landmark-update-naught-weights landmark-directions)
1496 (if landmark-debug
1497 (landmark-weights-debug)))
1498 (landmark-terminate-game nil))
1501 ;;;_ - landmark-start-robot ()
1502 (defun landmark-start-robot ()
1503 "Signal to the Landmark program that you have played.
1504 You must have put the cursor on the square where you want to play.
1505 If the game is finished, this command requests for another game."
1506 (interactive)
1507 (landmark-switch-to-window)
1508 (cond
1509 (landmark-emacs-is-computing
1510 (landmark-crash-game))
1511 ((not landmark-game-in-progress)
1512 (landmark-prompt-for-other-game))
1514 (let ((square (landmark-point-square)))
1515 (cond ((null square)
1516 (error "Your point is not on a square. Retry!"))
1517 ((not (zerop (aref landmark-board square)))
1518 (error "Your point is not on a free square. Retry!"))
1520 (progn
1521 (landmark-plot-square square 1)
1523 (landmark-store-old-y_t)
1524 (landmark-calc-current-smells)
1525 (put 'z 't (landmark-calc-smell-internal 'landmark-tree))
1527 (landmark-random-move)
1529 (landmark-calc-payoff)
1531 (mapc 'landmark-update-normal-weights landmark-directions)
1532 (mapc 'landmark-update-naught-weights landmark-directions)
1533 (landmark-amble-robot)
1534 )))))))
1537 ;;;_ + Misc functions
1538 ;;;_ - landmark-init (auto-start save-weights)
1539 (defvar landmark-tree-r "")
1541 (defun landmark-init (auto-start save-weights)
1543 (setq landmark-number-of-moves 0)
1545 (landmark-plot-landmarks)
1547 (if landmark-debug
1548 (save-current-buffer
1549 (set-buffer (get-buffer-create "*landmark-w0*"))
1550 (erase-buffer)
1551 (set-buffer (get-buffer-create "*landmark-moves*"))
1552 (set-buffer (get-buffer-create "*landmark-wts*"))
1553 (erase-buffer)
1554 (set-buffer (get-buffer-create "*landmark-y,s,noise*"))
1555 (erase-buffer)
1556 (set-buffer (get-buffer-create "*landmark-smell*"))
1557 (erase-buffer)
1558 (set-buffer (get-buffer-create "*landmark-blackbox*"))
1559 (erase-buffer)
1560 (set-buffer (get-buffer-create "*landmark-distance*"))
1561 (erase-buffer)))
1564 (landmark-set-landmark-signal-strengths)
1566 (dolist (direction landmark-directions)
1567 (put direction 'y_t 0.0))
1569 (if (not save-weights)
1570 (progn
1571 (mapc 'landmark-fix-weights-for landmark-directions)
1572 (dolist (direction landmark-directions)
1573 (put direction 'w0 landmark-initial-w0)))
1574 (message "Weights preserved for this run."))
1576 (if auto-start
1577 (progn
1578 (landmark-goto-xy (1+ (random landmark-board-width)) (1+ (random landmark-board-height)))
1579 (landmark-start-robot))))
1582 ;;;_ - something which doesn't work
1583 ; no-a-worka!!
1584 ;(defun landmark-sum-list (list)
1585 ; (if (> (length list) 0)
1586 ; (+ (car list) (landmark-sum-list (cdr list)))
1587 ; 0))
1588 ; this a worka!
1589 ; (eval (cons '+ list))
1590 ;;;_ - landmark-set-landmark-signal-strengths ()
1591 ;; on a screen higher than wide, I noticed that the robot would amble
1592 ;; left and right and not move forward. examining *landmark-blackbox*
1593 ;; revealed that there was no scent from the north and south
1594 ;; landmarks, hence, they need less factoring down of the effect of
1595 ;; distance on scent.
1597 (defun landmark-set-landmark-signal-strengths ()
1598 (setq landmark-tree-r (* (sqrt (+ (* landmark-cx landmark-cx)
1599 (* landmark-cy landmark-cy)))
1600 1.5))
1601 (mapc (lambda (direction)
1602 (put direction 'r (* landmark-cx 1.1)))
1603 landmark-ew)
1604 (mapc (lambda (direction)
1605 (put direction 'r (* landmark-cy 1.1)))
1606 landmark-ns)
1607 (put 'landmark-tree 'r landmark-tree-r))
1610 ;;;_ + landmark-test-run ()
1612 ;;;###autoload
1613 (defalias 'landmark-repeat 'landmark-test-run)
1614 ;;;###autoload
1615 (defun landmark-test-run ()
1616 "Run 100 Landmark games, each time saving the weights from the previous game."
1617 (interactive)
1618 (landmark 1)
1619 (dotimes (_ 100)
1620 (landmark 2)))
1622 ;;;###autoload
1623 (defun landmark (parg)
1624 "Start or resume an Landmark game.
1625 If a game is in progress, this command allows you to resume it.
1626 Here is the relation between prefix args and game options:
1628 prefix arg | robot is auto-started | weights are saved from last game
1629 ---------------------------------------------------------------------
1630 none / 1 | yes | no
1631 2 | yes | yes
1632 3 | no | yes
1633 4 | no | no
1635 You start by moving to a square and typing \\[landmark-start-robot],
1636 if you did not use a prefix arg to ask for automatic start.
1637 Use \\[describe-mode] for more info."
1638 (interactive "p")
1640 (setf landmark-n nil landmark-m nil)
1641 (landmark-switch-to-window)
1642 (cond
1643 (landmark-emacs-is-computing
1644 (landmark-crash-game))
1645 ((or (not landmark-game-in-progress)
1646 (<= landmark-number-of-moves 2))
1647 (let ((max-width (landmark-max-width))
1648 (max-height (landmark-max-height)))
1649 (or landmark-n (setq landmark-n max-width))
1650 (or landmark-m (setq landmark-m max-height))
1651 (cond ((< landmark-n 1)
1652 (error "I need at least 1 column"))
1653 ((< landmark-m 1)
1654 (error "I need at least 1 row"))
1655 ((> landmark-n max-width)
1656 (error "I cannot display %d columns in that window" landmark-n)))
1657 (if (and (> landmark-m max-height)
1658 (not (eq landmark-m landmark-saved-board-height))
1659 ;; Use EQ because SAVED-BOARD-HEIGHT may be nil
1660 (not (y-or-n-p (format "Do you really want %d rows? " landmark-m))))
1661 (setq landmark-m max-height)))
1662 (if landmark-one-moment-please
1663 (message "One moment, please..."))
1664 (landmark-start-game landmark-n landmark-m)
1665 (eval (cons 'landmark-init
1666 (cond
1667 ((= parg 1) '(t nil))
1668 ((= parg 2) '(t t))
1669 ((= parg 3) '(nil t))
1670 ((= parg 4) '(nil nil))
1671 (t '(nil t))))))))
1674 ;;;_ + Local variables
1676 ;;; The following `allout-layout' local variable setting:
1677 ;;; - closes all topics from the first topic to just before the third-to-last,
1678 ;;; - shows the children of the third to last (config vars)
1679 ;;; - and the second to last (code section),
1680 ;;; - and closes the last topic (this local-variables section).
1681 ;;;Local variables:
1682 ;;;allout-layout: (0 : -1 -1 0)
1683 ;;;End:
1685 (provide 'landmark)
1687 ;;; landmark.el ends here