TweetFollow Us on Twitter

Towers
Volume Number:2
Issue Number:1
Column Tag:Threaded Code

Animated Hanoi Towers in NEON

By Jörg Langowski, EMBL, c/o I.L.L., Grenoble Cedex, France, MacTutor Editorial Board

Lately, we have had a number of requests for a column on NEON. Since no neon articles have been forth coming, I have been asked to temporarily switch from my usual Forth ramblings to NEON. Since NEON is so close to Forth, we have decided to show a NEON example this month for a change. In light of this, we will re-name this column "Threaded Code" to cover all the Forth like object oriented languages that are Forth derivatives on the Mac.

The principles of object oriented programming have already been explained in several earlier columns (see LISP V1#6, NEON V1#8), so I am not going to dwell on that here. Rather, we are going to look at the famous Towers of Hanoi algorithm from an object-oriented point of view, gaining some on-hands experience with an example that - I feel - is particularly appropriate for this approach.

Let's recall: The 'towers' are three stacks of disks (Fig. 1). The leftmost one is filled with n disks stacked on top of one another in order of decreasing size, the other two are initially empty. The objective is to move the disks from the leftmost to the rightmost position, one by one, in such a way that a larger disk is never put on top of a smaller one. This works if one uses the middle position as a 'scratchpad' (try it out with pieces of paper), even though this is a rather tiresome procedure, if performed manually.

Fig. 1: Initial and final positions of Towers of Hanoi.

This is, of course, where Mac comes in; and the algorithm to solve the puzzle is very short if written recursively. In pseudo-Pascal it would look like this (see also John Bogan's Modula-2 column in V1#6):

procedure hanoi (n, start, inter, finish:integer);
    begin
     if n<>0 then 
 begin
 hanoi (n-1, start, finish, inter);
 move (n, start, finish);
 hanoi (n-1, inter, start, finish)
 end
    end;

where n is the number of disks, and start, inter and finish denote the starting, scratch and final positions for the disks. move is a procedure that (somehow) moves the disk from one stack to another.

OK, so if we set up a stack of disks, provide three towers to put them on to, and execute this procedure, we should be able to watch how Macintosh solves the Towers problem.

There are two things to notice: First, the definition is obviously recursive, second, we have to be careful how to represent our data.

Recursive definitions - NEON and MacForth

A very simple recursive procedure is the definition of the factorial of an integer number, which is given at the very beginning of the program example (listing 1). This definition works in NEON; you may refer to a word within the definition of the word itself (By the way, even if you weren't allowed to do it that way, you could resort to the forward declaration).

MacForth, however, sets the smudge bit in the vocabulary while compiling a new definition; therefore the word being defined is not known to the system at compile time and cannot be referred to by itself. You have probably seen the effect of the smudge bit already; when the compiler exits a declaration due to an error, words will show the first letter of the latest definition changed (in fact, it has the 8th bit set). One can easily circumvent this restriction by writing

: factorial   [ smudge ] 
   dup if dup 1- factorial * else drop 1 then ;
smudge

i.e., executing smudge during the compilation of factorial and resetting it afterwards. This will give a working definition, within the limit that is given by the 32-bit maximum integer size of the Macintosh.

Representation of disks and towers as NEON objects

Since we are, in fact, simulating material objects, moving them around and also displaying the result of our simulation on the screen, the Towers of Hanoi problem seems to be idealy suited for an object oriented language like NEON. We could define 'disks' as objects that can be drawn, put on top of other objects, called 'towers' and moved between them. The towers will automatically keep track of how many disks are on them, the disks will 'know' what tower they are on and how to 'draw themselves'.

The Three Towers

There is one predefined class in NEON, ordered-col, that represents a list of variable size. Elements of that list are 4-byte entities. A tower in our example will be an ordered-col of specified maximum size. In addition, it will have a certain position on the screen, which can be accessed by the methods getX: and getY: and a draw: method that draws the tower at its position in the current grafPort. That's all we need as a 'stacking device' for the disks. Everything else is taken care of by the disks themselves, as you will see soon.

The instance variables needed for every object of class tower are: rects that correspond to the base and the post, and ints that contain the x and y position of the center of the base.

Now we could start our simulation by creating three tower objects, e.g.

 tower babylon
 tower london
 tower pisa

Except for the fact that this looks cute, there is really no advantage in having named objects here. Just to make the point, and as an example how objects can be made to refer to other objects, we set up the three towers as a 3-element 4-byte array towers. This gives the additional advantage that we can refer to them by index. The array is initialized by the word make.towers, which shows how one can create 'nameless' objects on the heap with the heap> prefix (in my review copy of NEON, this information is hidden somewhere in the pages of Part III Chapter 1; I am confident that a revised manual will have this in the glossary).

xcenter ycenter ndisks heap> tower will leave on the stack the address of a new object of class tower created on the heap. The tower contains ndisks disks, and its base is centered at (xcenter,ycenter).

ndisks make.towers creates three of these gizmos equally spaced near the bottom of the screen, each of them having space for disks, but no disks on them yet. Their addresses are put into the array towers.

draw.towers will draw the towers, but not the disks. In this definition you see how one makes use of late binding; we want to send a draw: message to an object which is exactly known only at execution time (since towers could contain any kind of address). Therefore, if we want to draw the i-th tower, we have to write draw: [ i at: towers ] . (The same is true in immediate execution mode: draw: addr will abort with an error message, while draw: [ addr ] will do the correct thing, if addr is the address of a 'drawable' object. )

After you're finished with the example, you might want to dispose of them by calling dispose.towers. The same should be done to the disks; try writing a definition that will do the job.

Moving around the disks

The disk objects are more complicated than the towers. They have to be initialized and drawn; they will come in different sizes; and they will move around, sitting on one of the three stacks at any given time.

Since the disks won't shrink or grow, their size is known at initialization time and will be passed as a parameter to classinit:. This method also needs to know which tower the disk is on at the beginning (we pass the address of the tower object and put it into the instance variable which). The newly created disk it then put on top of the tower which it is associated with.

The draw: method is not quite general for disks, but very specialized for Hanoi disks: it makes use of the fact that a disk is only drawn right after it has been put on top of a stack. Since the size of that stack is known (by executing size: [ get: which ] ), the position of the topmost disk is exactly determined. Therefore, draw: calculates first the coordinates of the center of the disk and saves them in instance variables for later use, then does the necessary Quickdraw calls. If one wanted to do other things with the disks, e.g. drawing them at different places, one might want to factor out the code that calculates the coordinates.

undraw: removes the disk from its position (but not from the list which is being kept in the tower), and redraws the little black rectangle, the part of the post that had been overwritten previously. Here again, you see that a special assumption about the behavior of the disk is made: namely, that it does not cover anything but a certain part of the tower post.

dest move: finally will move a disk from wherever it was to the tower dest, undrawing and redrawing as necessary.

Object Interdependence

You see the line that we draw between general and specialized behavior of objects. The fact that a disk is displayed as a pattern-filled rectangle that takes up a certain amount of space on the screen is a behavior that would be general to any 'disk-like' object (unless we choose to rotate it as well). Association to another object, the tower, would also be something that could be implemented into an idealized 'general' disk. But the fact that this other object has a certain shape and that the disk can only be put onto it in a certain manner is extra information which the disk 'knows' about and which is used within the code that defines some of its methods.

To make the objects even more independent, 'MacDraw-like', would require a much more sophisticated interface between towers and disks than given here. One would then rather start by defining a subclass of window which has e.g. an ordered-col of objects associated to it, and which would be updated each time one of the objects is moved. I felt this would have created too much overhead to the program example. But you can see that MacDraw is not very far away, just go ahead and create that window, a set of objects and their appropriate behavior, and there you go... send us the code when you're done, we'll publish it.

Main routine

The main routine simply creates a Hanoi puzzle of ndisks disks and draws the initial position. ndisks i j k hanoi will move those disks ( or less, if you set ndisks differently) according to the rules of the game from tower i via j to k. Try

10 main
10 0 1 2 hanoi

or, to create a 'forbidden' pattern

10 main
5 0 1 2 hanoi
5 0 2 1 hanoi
5 1 0 2 hanoi

Have fun! Determined FORTH programmers might try to rewrite this example into MacForth or some other Forth. The Hanoi routine itself is simple. Doing the data representation in the same way should look rather more complicated...

Change of address

We have moved in the meantime. Please address all questions, remarks, suggestions, etc. regarding this column to:

Jörg Langowski

EMBL, c/o I.L.L., 156X

F-38042 Grenoble Cedex

France

Listing 1: Towers of Hanoi code
( © 110285 MacTutor by JL )
: factorial   dup if dup 1- factorial * else drop 1 then ;

:class tower <super ordered-col
        rect base
        rect column
        int xcenter
        int ycenter

    :M classinit: ( xcenter ycenter -- )
            put: ycenter put: xcenter 
            get: xcenter 70 -  get: ycenter 16 - 
            get: xcenter 70 +  get: ycenter   put: base
            get: xcenter 4 -   get: ycenter 
 limit: self 10 * 50 +  -
            get: xcenter 4 +   get: ycenter 16 - 
 put: column 
    ;M

    :M draw:  0 syspat dup fill: base fill: column ;M
    :M getX:   get: xcenter ;M
    :M getY:   get: ycenter ;M

;class

:class disk  <super object
        int size
        var which
        rect image
        int xc  int yc
    :M classinit: ( which size -- )   
                    put: size  put: which 
                    addr: self  add: [ get: which ] ;M
    :M draw: 
            getX: [ get: which ] put: xc 
            getY: [ get: which ] 
                 12 - size: [ get: which ] 10 * - put: yc
            get: xc get: size -  get: yc 4-   
            get: xc get: size +  get: yc 4+  put: image
            3 syspat fill: image  draw: image 
    ;M

    :M undraw: 19 syspat fill: image
            get: xc 4- get: yc 4- 
            get: xc 4+ get: yc 4+  put: image
            0 syspat fill: image
    ;M

    :M move: { dest -- }
            undraw: self
            addr: self add: [ dest ]
            size: [ get: which ] 1-  
            remove: [ get: which ]
            dest put: which   draw: self
    ;M
;class
3 array towers
: make.towers { ndisks -- }
   3 0 do 
      i 150 * 100 +  280 ndisks  heap> tower  
      i to: towers  loop ;

: draw.towers
   3 0 do draw: [ i at: towers ] loop ;

: dispose.towers   3 0 do  i dispose: towers loop ;

: hanoi { n start inter finish -- }
   n if   n 1-  start finish inter hanoi
          finish at: towers  
               move: [ last: [ start at: towers ] ]   
          n 1-   inter start finish hanoi
     then
;
: main  { ndisks -- }
    ndisks make.towers  cls draw.towers
    ndisks 0 do 
       0 at: towers 6 ndisks i - 4* + heap> disk drop 
                       draw: [ last: [ 0 at: towers ] ] loop
;
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.