home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 9 / 09.iso / l / l074 / 1.ddi / HANOI.TRU < prev    next >
Encoding:
Text File  |  1984-12-03  |  2.2 KB  |  101 lines

  1. ! Towers of Hanoi
  2. !
  3. ! a True BASIC(tm), Inc. product
  4. !
  5. ! ABSTRACT
  6. !    Hanoi is an animated illustration of the Towers
  7. !    of Hanoi problem, in which a series of disks must
  8. !    be moved from one peg to another, without ever
  9. !    putting a larger disk on top of a smaller one.
  10. !    Hanoi demonstrates the use of recursion in True BASIC.
  11. !    Most of the work is done within the recursive
  12. !    subroutine `Hanoi'.  Other subroutines are primarily
  13. !    for handling the graphics.
  14. !
  15. ! Copyright (c) 1985 by True BASIC, Inc.
  16.  
  17. DIM count(0 to 6,3)               ! For graphics
  18. CALL initial(#3)
  19. WINDOW #3
  20.  
  21. LET disks = 6
  22. LET count(0,1) = disks            ! All on disk 1
  23. FOR i = 1 to disks
  24.     LET count(i,1) = disks+1-i
  25. NEXT i
  26. CALL setup(disks)
  27. CALL hanoi(disks,1,2,3,count)
  28. CALL ending
  29.  
  30. END
  31.  
  32. SUB setup(n)                      ! Disks on no. 1
  33.     SET COLOR 1
  34. BOX AREA 0,4,0,1
  35.     SET COLOR 3
  36.     FOR i = 1 to 3
  37.         BOX AREA i-.02,i+.02,1.05,7
  38.     NEXT i
  39.     FOR j = n to 1 step -1
  40.         CALL disk(1,n+1-j,j,2)
  41.     NEXT j
  42.  
  43. END SUB
  44.  
  45. SUB hanoi(n,a,b,c,count(,))             ! Recursive routine
  46.     IF n = 1 then
  47.        CALL move(a,b,count)
  48.     ELSE
  49.        CALL hanoi(n-1,a,c,b,count)
  50.        CALL move(a,b,count)
  51.        CALL hanoi(n-1,c,b,a,count)
  52.     END IF
  53. END SUB
  54.  
  55. SUB disk(d,h,s,c)                 ! Disk no., height, size, color
  56.     LET x1 = d - (s+1)/15
  57.     LET x2 = d + (s+1)/15
  58.     LET y1 = 1 + h-1
  59.     LET y2 = 1 + h
  60.     SET COLOR c
  61.     BOX AREA x1,x2,y1+.05,y2
  62.     IF c = 0 then
  63.        SET COLOR 3
  64.        BOX AREA d-.02,d+.02,y1+.05,y2
  65.     END IF
  66.     PAUSE .2
  67. END SUB
  68.  
  69. SUB move(a,b,c(,))
  70.     LET n = c(0,a)
  71.     LET n2 = c(0,b)
  72.     LET s = c(n,a)
  73.     CALL disk(a,n,s,0)            ! Erase
  74.     CALL disk(b,n2+1,s,2)         ! Draw
  75.     LET c(0,a) = n-1
  76.     LET c(0,b) = n2+1
  77.     LET c(n2+1,b) = s
  78. END SUB
  79.  
  80. SUB initial(#1)
  81.  
  82.     SET MODE "graphics"
  83.     OPEN #1: screen .1875,.8125,.2,.8
  84.     SET WINDOW 0,4,0,8
  85.     SET BACK 17
  86.     SET COLOR 1
  87.     PLOT TEXT, at .5,10: "The Towers of Hanoi"
  88.  
  89. END SUB
  90.  
  91. SUB ending
  92.  
  93.     PLOT TEXT, at .5,-2: "  N I R V A N A "
  94.     FOR i = 1 to 31
  95.         PAUSE .2
  96.         LET c = mod(i,3)*3 +14
  97.         SET BACK c
  98.     NEXT i
  99.  
  100. END SUB
  101.