Towers of Hanoi Graphic (well, "ASCII - Graphic") Output


#1

This post references the “Linear Data Structures” project. Here is a function that will present each round as a series of underscores formatted to resemble the disks:

___                           
____          _                   
_____         __                  
L             M           R

To use it, you need access to the status of each stack at any given time. The function, print_items() in the stack.py module provides this information, but outputs it in a printed format that is not too useful. There are a couple of ways to get at the underlying information. I chose to simply change the output of that function from print() to return. So

  1. In that function, comment out the last two lines:
        print_list.reverse()
        print("{0} Stack: {1}".format(self.get_name(), print_list))
  1. … and add the line
    return print_list

  2. Now, in the towers_of_hanoi.py module, under the heading # Play the Game, comment out the lines

    for stack in stacks:
        stack.print_items()
  1. … and replace them with:
    print_pix()

  2. Finally, copy the entire function below, and paste it into your towers_of_hanoi.py module somewhere above #Play the Game

def print_pix():
    # render current state as a list of lists of values
    show_list = []
    for stack in stacks:        
        show_list.append(stack.print_items())       
    # pad lists with leading zeros so all are length = num_dusks
    for idx, item in enumerate(show_list):
        new_list = [0 for i in range(num_disks - len(item))]
        show_list[idx] = new_list + show_list[idx]    
    # print num_disks lines, each comprised of
    # ... three columns, correspunding to "L", "M", and "R".
    # ... Each column will consist of a number of underscores
    # ... corresponding to the value of the node at that level.
    for i in range(num_disks):
        for item in show_list:           
            mult = item[i]
            s = "_" * mult
            print("{:10}".format(s), end = '')
        print()
    
    print("{:10}{:10}{:10}\n".format("L","M","R"))

I hope you enjoy it!

P.S. : Tired of trying to solve that 7-ring tower? Try this!


Towers of Hanoi - Watch it unfold through recursion!