\ hanoi.4th
\
\ Towers of Hanoi puzzle
\
\ From a posting to comp.lang.forth, 30 May 2002, by Marcel
\ Hendrix and Brad Eckert. According to Marcel Hendrix, the
\ code for the HANOI algorithm was originally posted to clf
\ by Raul Deluth Miller in 1994.
\ ---------------------------------------------------------------------------
\ kForth includes and defs (2002-05-30 K. Myneni)
\
include strings
include ansi
: chars ;
\ ---------------------------------------------------------------------------
\ To run under other ANS Forths, uncomment the defs below:
\ : a@ @ ;
\ : ?allot here swap allot ;
\ : nondeferred ;
variable slowness 1000 slowness ! \ ms delay between screen updates
create PegSPS 3 cells allot \ pointers for three disk stacks
: ShowPegs ( -- ) page 3 0 do i showpeg loop slowness @ ms
key? if key drop 0 11 at-xy ." Stopped" cr abort then ;
: MoveRing ( ring -- ring ) dup to! 3 / pop over fro! 3 mod push
ShowPegs ;
: HANOI ( depth direction -- depth direction ) swap 1- swap
over IF to! recurse to! MoveRing fro! recurse fro!
ELSE MoveRing
THEN swap 1+ swap ;
: PLAY ( depth -- )
3 0 DO i PegClr LOOP \ clear the pegs
dup BEGIN ?dup WHILE 1- dup 0 push REPEAT \ stack up some disks
showpegs 1 HANOI 2drop \ move them
0 11 at-xy ;