4 ; Copyright © 2016 Keith Packard <keithp@keithp.com>
6 ; This program is free software; you can redistribute it and/or modify
7 ; it under the terms of the GNU General Public License as published by
8 ; the Free Software Foundation, either version 2 of the License, or
9 ; (at your option) any later version.
11 ; This program is distributed in the hope that it will be useful, but
12 ; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ; General Public License for more details.
17 ; ANSI control sequences
19 (defun move-to (col row)
20 (patom "\033[" row ";" col "H" nil)
27 (defun display-string (x y str)
32 ; Here's the pieces to display
34 (setq stack '(" * " " *** " " ***** " " ******* " " ********* " "***********"))
36 ; Here's all of the stacks of pieces
37 ; This is generated when the program is run
41 ; Display one stack, clearing any
44 (defun display-stack (x y clear stack)
47 (display-string x y (car stack))
48 (display-stack x (1+ y) 0 (cdr stack))
54 (display-string x y " ")
55 (display-stack x (1+ y) (1- clear) stack)
61 ; Position of the top of the stack on the screen
62 ; Shorter stacks start further down the screen
64 (defun stack-pos (y stack)
68 ; Display all of the stacks, spaced 20 columns apart
70 (defun display-stacks (x y stacks)
72 (display-stack x 0 (stack-pos y (car stacks)) (car stacks))
73 (display-stacks (+ x 20) y (cdr stacks)))
78 ; Display all of the stacks, then move the cursor
79 ; out of the way and flush the output
82 (display-stacks 0 top stacks)
87 ; Reset stacks to the starting state, with
88 ; all of the pieces in the first stack and the
91 (defun reset-stacks ()
92 (setq stacks (list stack nil nil))
93 (setq top (+ (length stack) 3))
97 ; more functions which could usefully
106 ; Replace a stack in the list of stacks
109 (defun replace (list pos member)
110 (cond ((= pos 0) (cons member (cdr list)))
111 ((cons (car list) (replace (cdr list) (1- pos) member)))
115 ; Move a piece from the top of one stack
116 ; to the top of another
118 (defun move-piece (from to)
119 (let ((from-stack (nth stacks from))
120 (to-stack (nth stacks to))
121 (piece (car from-stack)))
122 (setq from-stack (cdr from-stack))
123 (setq to-stack (cons piece to-stack))
124 (setq stacks (replace stacks from from-stack))
125 (setq stacks (replace stacks to to-stack))
131 ; The implementation of the game
133 (defun _hanoi (n from to use)
141 (_hanoi (1- n) from use to)
142 (_hanoi 1 from to use)
143 (_hanoi (1- n) use to from)
149 ; A pretty interface which
150 ; resets the state of the game,
151 ; clears the screen and runs
155 (setq len (reset-stacks))
160 ; Run many in a row to time them