]> code.delx.au - gnu-emacs/blob - lisp/play/mpuz.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / lisp / play / mpuz.el
1 ;;; mpuz.el --- multiplication puzzle for GNU Emacs
2
3 ;; Copyright (C) 1990, 2001-2011 Free Software Foundation, Inc.
4
5 ;; Author: Philippe Schnoebelen <phs@lsv.ens-cachan.fr>
6 ;; Overhauled: Daniel Pfeiffer <occitan@esperanto.org>
7 ;; Keywords: games
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; `M-x mpuz' generates a random multiplication puzzle. This is a
27 ;; multiplication example in which each digit has been consistently replaced
28 ;; with some letter. Your job is to reconstruct the original digits. Type
29 ;; `?' while the mode is active for detailed help.
30
31 ;;; Code:
32
33 (defgroup mpuz nil
34 "Multiplication puzzle."
35 :prefix "mpuz-"
36 :group 'games)
37
38 (random t) ; randomize
39
40 (defcustom mpuz-silent 'error
41 "Set this to nil if you want dings on inputs.
42 t means never ding, and `error' means only ding on wrong input."
43 :type '(choice (const :tag "No" nil)
44 (const :tag "Yes" t)
45 (const :tag "If correct" error))
46 :group 'mpuz)
47
48 (defcustom mpuz-solve-when-trivial t
49 "Solve any row that can be trivially calculated from what you've found."
50 :type 'boolean
51 :group 'mpuz)
52
53 (defcustom mpuz-allow-double-multiplicator nil
54 "Allow 2nd factors like 33 or 77."
55 :type 'boolean
56 :group 'mpuz)
57
58 (defface mpuz-unsolved
59 '((((class color)) (:foreground "red1" :bold t))
60 (t (:bold t)))
61 "Face to use for letters to be solved."
62 :group 'mpuz)
63
64 (defface mpuz-solved
65 '((((class color)) (:foreground "green1" :bold t))
66 (t (:bold t)))
67 "Face to use for solved digits."
68 :group 'mpuz)
69
70 (defface mpuz-trivial
71 '((((class color)) (:foreground "blue" :bold t))
72 (t (:bold t)))
73 "Face to use for trivial digits solved for you."
74 :group 'mpuz)
75
76 (defface mpuz-text
77 '((t (:inherit variable-pitch)))
78 "Face to use for text on right."
79 :group 'mpuz)
80
81 \f
82 ;; Mpuz mode and keymaps
83 ;;----------------------
84 (defcustom mpuz-mode-hook nil
85 "Hook to run upon entry to mpuz."
86 :type 'hook
87 :group 'mpuz)
88
89 (defvar mpuz-mode-map
90 (let ((map (make-sparse-keymap)))
91 (define-key map "a" 'mpuz-try-letter)
92 (define-key map "b" 'mpuz-try-letter)
93 (define-key map "c" 'mpuz-try-letter)
94 (define-key map "d" 'mpuz-try-letter)
95 (define-key map "e" 'mpuz-try-letter)
96 (define-key map "f" 'mpuz-try-letter)
97 (define-key map "g" 'mpuz-try-letter)
98 (define-key map "h" 'mpuz-try-letter)
99 (define-key map "i" 'mpuz-try-letter)
100 (define-key map "j" 'mpuz-try-letter)
101 (define-key map "A" 'mpuz-try-letter)
102 (define-key map "B" 'mpuz-try-letter)
103 (define-key map "C" 'mpuz-try-letter)
104 (define-key map "D" 'mpuz-try-letter)
105 (define-key map "E" 'mpuz-try-letter)
106 (define-key map "F" 'mpuz-try-letter)
107 (define-key map "G" 'mpuz-try-letter)
108 (define-key map "H" 'mpuz-try-letter)
109 (define-key map "I" 'mpuz-try-letter)
110 (define-key map "J" 'mpuz-try-letter)
111 (define-key map "\C-g" 'mpuz-offer-abort)
112 (define-key map "?" 'describe-mode)
113 map)
114 "Local keymap to use in Mult Puzzle.")
115
116
117
118 (defun mpuz-mode ()
119 "Multiplication puzzle mode.
120
121 You have to guess which letters stand for which digits in the
122 multiplication displayed inside the `*Mult Puzzle*' buffer.
123
124 You may enter a guess for a letter's value by typing first the letter,
125 then the digit. Thus, to guess that A=3, type `A 3'.
126
127 To leave the game to do other editing work, just switch buffers.
128 Then you may resume the game with M-x mpuz.
129 You may abort a game by typing \\<mpuz-mode-map>\\[mpuz-offer-abort]."
130 (interactive)
131 (kill-all-local-variables)
132 (setq major-mode 'mpuz-mode
133 mode-name "Mult Puzzle"
134 tab-width 30)
135 (use-local-map mpuz-mode-map)
136 (run-mode-hooks 'mpuz-mode-hook))
137
138 \f
139 ;; Some variables for statistics
140 ;;------------------------------
141 (defvar mpuz-nb-errors 0
142 "Number of errors made in current game.")
143
144 (defvar mpuz-nb-completed-games 0
145 "Number of games completed.")
146
147 (defvar mpuz-nb-cumulated-errors 0
148 "Number of errors made in previous games.")
149
150
151 ;; Some variables for game tracking
152 ;;---------------------------------
153 (defvar mpuz-in-progress nil
154 "True if a game is currently in progress.")
155
156 (defvar mpuz-found-digits (make-bool-vector 10 nil)
157 "A vector recording which digits have been decrypted.")
158
159 (defvar mpuz-trivial-digits (make-bool-vector 10 nil)
160 "A vector recording which digits have been solved for you.")
161
162 (defmacro mpuz-digit-solved-p (digit)
163 `(or (aref mpuz-found-digits ,digit)
164 (aref mpuz-trivial-digits ,digit)))
165
166
167 ;; A puzzle uses a permutation of [0..9] into itself.
168 ;; We use both the permutation and its inverse.
169 ;;---------------------------------------------------
170 (defvar mpuz-digit-to-letter (make-vector 10 0)
171 "A permutation from [0..9] to [0..9].")
172
173 (defvar mpuz-letter-to-digit (make-vector 10 0)
174 "The inverse of mpuz-digit-to-letter.")
175
176 (defmacro mpuz-to-digit (letter)
177 (list 'aref 'mpuz-letter-to-digit letter))
178
179 (defmacro mpuz-to-letter (digit)
180 (list 'aref 'mpuz-digit-to-letter digit))
181
182 (defun mpuz-build-random-perm ()
183 "Initialize puzzle coding with a random permutation."
184 (let ((letters (list 0 1 2 3 4 5 6 7 8 9)) ; new cons cells, because of delq
185 (index 10)
186 elem)
187 (while letters
188 (setq elem (nth (random index) letters)
189 letters (delq elem letters)
190 index (1- index))
191 (aset mpuz-digit-to-letter index elem)
192 (aset mpuz-letter-to-digit elem index))))
193
194
195 ;; A puzzle also uses a board displaying a multiplication.
196 ;; Every digit appears in the board, crypted or not.
197 ;;------------------------------------------------------
198 (defvar mpuz-board (make-vector 10 nil)
199 "The board associates to any digit the list of squares where it appears.")
200
201 (defun mpuz-put-number-on-board (number row &rest l)
202 "Put (last digit of) NUMBER on ROW and COLUMNS of the puzzle board."
203 (let (digit)
204 (while l
205 (setq digit (% number 10)
206 number (/ number 10))
207 (aset mpuz-board digit `((,row . ,(car l)) ,@(aref mpuz-board digit)))
208 (setq l (cdr l)))))
209
210 (defun mpuz-check-all-solved (&optional row col)
211 "Check whether all digits have been solved. Return t if yes."
212 (catch 'solved
213 (let (A B1 B2 C D E squares)
214 (and mpuz-solve-when-trivial
215 (not row)
216 (while
217 (cond ((or (and (setq B1 (or B1 (mpuz-check-all-solved 4 7))
218 B2 (or B2 (mpuz-check-all-solved 4 9))
219 E (or E (mpuz-check-all-solved 10))
220 A (or A (mpuz-check-all-solved 2)))
221 B1 B2)
222 (and E (or A (and B1 B2))))
223 (mpuz-solve)
224 (mpuz-paint-board)
225 (throw 'solved t))
226 ((and (setq D (or D (mpuz-check-all-solved 8))
227 C (or C (mpuz-check-all-solved 6)))
228 D (not E))
229 (mpuz-solve 10))
230 ((and E (not (eq C D)))
231 (mpuz-solve (if D 6 8)))
232 ((and A (not (eq B2 C)))
233 (mpuz-solve (if C 4 6) (if C 9)))
234 ((and A (not (eq B1 D)))
235 (mpuz-solve (if D 4 8) (if D 7)))
236 ((and (not A) (or (and B2 C) (and B1 D)))
237 (mpuz-solve 2)))))
238 (mpuz-paint-board)
239 (mapc (lambda (digit)
240 (and (not (mpuz-digit-solved-p digit)) ; unsolved
241 (setq squares (aref mpuz-board digit))
242 (if row
243 (if col
244 (member (cons row col) squares)
245 (assq row squares))
246 squares) ; and appearing in the puzzle!
247 (throw 'solved nil)))
248 [0 1 2 3 4 5 6 7 8 9]))
249 t))
250
251
252 ;; To build a puzzle, we take two random numbers and multiply them.
253 ;; We also take a random permutation for encryption.
254 ;; The random numbers are only use to see which digit appears in which square
255 ;; of the board. Everything is stored in individual squares.
256 ;;---------------------------------------------------------------------------
257 (defun mpuz-random-puzzle ()
258 "Draw random values to be multiplied in a puzzle."
259 (mpuz-build-random-perm)
260 (fillarray mpuz-board nil) ; erase the board
261 ;; A,B,C,D & E, are the five rows of our multiplication.
262 ;; Choose random values, discarding cases with leading zeros in C or D.
263 (let* ((A (if mpuz-allow-double-multiplicator (+ 112 (random 888))
264 (+ 125 (random 875))))
265 (min (1+ (/ 999 A)))
266 (B1 (+ min (random (- 10 min))))
267 B2 C D E)
268 (while (if (= B1 (setq B2 (+ min (random (- 10 min)))))
269 (not mpuz-allow-double-multiplicator)))
270 (setq C (* A B2)
271 D (* A B1)
272 E (+ C (* D 10)))
273 ;; Individual digits are now put on their respective squares.
274 ;; [NB: A square is a pair (row . column) of the screen.]
275 (mpuz-put-number-on-board A 2 9 7 5)
276 (mpuz-put-number-on-board (+ (* B1 10) B2) 4 9 7)
277 (mpuz-put-number-on-board C 6 9 7 5 3)
278 (mpuz-put-number-on-board D 8 7 5 3 1)
279 (mpuz-put-number-on-board E 10 9 7 5 3 1)))
280 \f
281 ;; Display
282 ;;--------
283 (defconst mpuz-framework
284 "
285 . . .
286 Number of errors (this game): 0
287 x . .
288 -------
289 . . . .
290 Number of completed games: 0
291 . . . .
292 --------- Average number of errors: 0.00
293 . . . . ."
294 "The general picture of the puzzle screen, as a string.")
295
296 (defun mpuz-create-buffer ()
297 "Create (or recreate) the puzzle buffer. Return it."
298 (let ((buf (get-buffer-create "*Mult Puzzle*"))
299 (face '(face mpuz-text))
300 buffer-read-only)
301 (with-current-buffer buf
302 (erase-buffer)
303 (insert mpuz-framework)
304 (set-text-properties 13 42 face)
305 (set-text-properties 79 105 face)
306 (set-text-properties 128 153 face)
307 (mpuz-paint-board)
308 (mpuz-paint-errors)
309 (mpuz-paint-statistics))
310 buf))
311
312 (defun mpuz-paint-number (n &optional eol words)
313 (end-of-line eol)
314 (let (buffer-read-only)
315 (delete-region (point)
316 (progn (backward-word (or words 1)) (point)))
317 (insert n)))
318
319 (defun mpuz-paint-errors ()
320 "Paint error count on the puzzle screen."
321 (mpuz-switch-to-window)
322 (goto-char (point-min))
323 (forward-line 2)
324 (mpuz-paint-number (prin1-to-string mpuz-nb-errors)))
325
326 (defun mpuz-paint-statistics ()
327 "Paint statistics about previous games on the puzzle screen."
328 (goto-char (point-min))
329 (forward-line 6)
330 (mpuz-paint-number (prin1-to-string mpuz-nb-completed-games))
331 (mpuz-paint-number
332 (format "%.2f"
333 (if (zerop mpuz-nb-completed-games)
334 0
335 (/ (+ 0.0 mpuz-nb-cumulated-errors)
336 mpuz-nb-completed-games)))
337 3 2))
338
339 (defun mpuz-paint-board ()
340 "Paint board situation on the puzzle screen."
341 (mpuz-switch-to-window)
342 (mapc 'mpuz-paint-digit [0 1 2 3 4 5 6 7 8 9])
343 (goto-char (point-min)))
344
345 (defun mpuz-paint-digit (digit)
346 "Paint all occurrences of DIGIT on the puzzle board."
347 (let ((char (if (mpuz-digit-solved-p digit)
348 (+ digit ?0)
349 (+ (mpuz-to-letter digit) ?A)))
350 (face `(face
351 ,(cond ((aref mpuz-trivial-digits digit) 'mpuz-trivial)
352 ((aref mpuz-found-digits digit) 'mpuz-solved)
353 ('mpuz-unsolved))))
354 buffer-read-only)
355 (mapc (lambda (square)
356 (goto-char (point-min))
357 (forward-line (1- (car square))) ; line before column!
358 (move-to-column (cdr square))
359 (insert char)
360 (set-text-properties (1- (point)) (point) face)
361 (delete-char 1))
362 (aref mpuz-board digit))))
363
364 (defun mpuz-get-buffer ()
365 "Get the puzzle buffer if it exists."
366 (get-buffer "*Mult Puzzle*"))
367
368 (defun mpuz-switch-to-window ()
369 "Find or create the Mult-Puzzle buffer, and display it."
370 (let ((buf (mpuz-get-buffer)))
371 (or buf (setq buf (mpuz-create-buffer)))
372 (switch-to-buffer buf)
373 (setq buffer-read-only t)
374 (mpuz-mode)))
375
376 \f
377 ;; Game control
378 ;;-------------
379 (defun mpuz-start-new-game ()
380 "Start a new puzzle."
381 (message "Here we go...")
382 (setq mpuz-nb-errors 0
383 mpuz-in-progress t)
384 (fillarray mpuz-found-digits nil) ; initialize mpuz-found-digits
385 (fillarray mpuz-trivial-digits nil)
386 (mpuz-random-puzzle)
387 (mpuz-switch-to-window)
388 (mpuz-paint-board)
389 (mpuz-paint-errors)
390 (mpuz-ask-for-try))
391
392 ;;;###autoload
393 (defun mpuz ()
394 "Multiplication puzzle with GNU Emacs."
395 ;; Main entry point
396 (interactive)
397 (mpuz-switch-to-window)
398 (if mpuz-in-progress
399 (mpuz-offer-abort)
400 (mpuz-start-new-game)))
401
402 (defun mpuz-offer-abort ()
403 "Ask if user wants to abort current puzzle."
404 (interactive)
405 (if (y-or-n-p "Abort game? ")
406 (let ((buf (mpuz-get-buffer)))
407 (message "Mult Puzzle aborted.")
408 (setq mpuz-in-progress nil
409 mpuz-nb-errors 0)
410 (fillarray mpuz-board nil)
411 (if buf (kill-buffer buf)))
412 (mpuz-ask-for-try)))
413
414 (defun mpuz-ask-for-try ()
415 "Ask for user proposal in puzzle."
416 (message "Your try?"))
417
418 (defun mpuz-ding (error)
419 "Dings, unless global variable `mpuz-silent' forbids it."
420 (cond ((eq mpuz-silent t))
421 ((not mpuz-silent) (ding t))
422 (error (ding t))))
423
424 (defun mpuz-try-letter ()
425 "Propose a digit for a letter in puzzle."
426 (interactive)
427 (if mpuz-in-progress
428 (let (letter-char digit digit-char message)
429 (setq letter-char (upcase last-command-event)
430 digit (mpuz-to-digit (- letter-char ?A)))
431 (cond ((mpuz-digit-solved-p digit)
432 (message "%c already solved." letter-char)
433 (mpuz-ding t))
434 ((null (aref mpuz-board digit))
435 (message "%c does not appear." letter-char)
436 (mpuz-ding t))
437 ((progn (message "%c = " letter-char)
438 ;; <char> has been entered.
439 ;; Print "<char> =" and
440 ;; read <num> or = <num>
441 (setq digit-char (read-char))
442 (if (eq digit-char ?=)
443 (setq digit-char (read-char)))
444 (or (> digit-char ?9) (< digit-char ?0))) ; bad input
445 (message "%c = %c" letter-char digit-char)
446 (mpuz-ding t))
447 (t
448 (mpuz-try-proposal letter-char digit-char))))
449 (if (y-or-n-p "Start a new game? ")
450 (mpuz-start-new-game)
451 (message "OK. I won't."))))
452
453 (defun mpuz-try-proposal (letter-char digit-char)
454 "Propose LETTER-CHAR as code for DIGIT-CHAR."
455 (let* ((letter (- letter-char ?A))
456 (digit (- digit-char ?0))
457 (correct-digit (mpuz-to-digit letter))
458 (game mpuz-nb-completed-games))
459 (cond ((mpuz-digit-solved-p correct-digit)
460 (message "%c has already been found." (+ correct-digit ?0)))
461 ((mpuz-digit-solved-p digit)
462 (message "%c has already been placed." digit-char))
463 ((= digit correct-digit)
464 (message "%c = %c correct!" letter-char digit-char)
465 (mpuz-ding nil)
466 (aset mpuz-found-digits digit t) ; Mark digit as solved
467 (and (mpuz-check-all-solved)
468 (mpuz-close-game)))
469 (t ;;; incorrect guess
470 (message "%c = %c incorrect!" letter-char digit-char)
471 (mpuz-ding t)
472 (setq mpuz-nb-errors (1+ mpuz-nb-errors))
473 (mpuz-paint-errors)))))
474
475 (defun mpuz-close-game ()
476 "Housecleaning when puzzle has been solved."
477 (setq mpuz-in-progress nil
478 mpuz-nb-cumulated-errors (+ mpuz-nb-cumulated-errors mpuz-nb-errors)
479 mpuz-nb-completed-games (1+ mpuz-nb-completed-games))
480 (mpuz-paint-statistics)
481 (let ((message (format "Puzzle solved with %d error%s. That's %s"
482 mpuz-nb-errors
483 (if (= mpuz-nb-errors 1) "" "s")
484 (cond ((= mpuz-nb-errors 0) "perfect!")
485 ((= mpuz-nb-errors 1) "very good!")
486 ((= mpuz-nb-errors 2) "good.")
487 ((= mpuz-nb-errors 3) "not bad.")
488 ((= mpuz-nb-errors 4) "not too bad...")
489 ((< mpuz-nb-errors 10) "bad!")
490 ((< mpuz-nb-errors 15) "awful.")
491 (t "not serious.")))))
492 (message "%s" message)
493 (sit-for 4)
494 (if (y-or-n-p (concat message " Start a new game? "))
495 (mpuz-start-new-game)
496 (message "Good Bye!"))))
497
498 (defun mpuz-solve (&optional row col)
499 "Find solution for autosolving."
500 (mapc (lambda (digit)
501 (or (mpuz-digit-solved-p digit)
502 (if row
503 (not (if col
504 (member (cons row col) (aref mpuz-board digit))
505 (assq row (aref mpuz-board digit)))))
506 (aset mpuz-trivial-digits digit t)))
507 [0 1 2 3 4 5 6 7 8 9])
508 t)
509
510 (defun mpuz-show-solution (row)
511 "Display solution for debugging purposes."
512 (interactive "P")
513 (mpuz-switch-to-window)
514 (mpuz-solve (if row (* 2 (prefix-numeric-value row))))
515 (mpuz-paint-board)
516 (if (mpuz-check-all-solved)
517 (mpuz-close-game)))
518
519 (provide 'mpuz)
520
521 ;;; mpuz.el ends here