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