# Tower of Hanoi

Page 1 of 1

## 10 Replies - 1734 Views - Last Post: 05 July 2018 - 01:27 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=411686&amp;s=c00cf789838d9d24a9570129e778aa66&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Sachsen31

Reputation: 0
• Posts: 4
• Joined: 05-July 18

# Tower of Hanoi

Posted 05 July 2018 - 01:30 AM

Hy guys!

I want to make a Tower of Hanoi game, so no simulation.
We got this code from our Tutor.

```# Print start
A = [3, 2, 1]
B = []
C = []

print str(A) + str(B)/>/> + str(C)
print "##############"
print "\n"

def move(n, source, target, auxiliary):
if n > 0:
# move n - 1 disks from source to auxiliary, so they are out of the way
move(n - 1, source, auxiliary, target)

# move the nth disk from source to target
target.append(source.pop())

# Display our progress
print str(A) + str(B)/>/> + str(C)
print "##############"
print "\n"
# move the n - 1 disks that we left on auxiliary onto target
move(n - 1, auxiliary, target, source)

# initiate call from source A to target C with auxiliary B
move(3, A, C, B)/>/>

```

So I understand the code pretty well, but I donīt like to just look at the answers of a simulation.
I want to create a game, so a person can decide which disk they want to move to which tower and so on.

I donīt really know if it is maybe a bit to diffucult to solve this problem, because I just work with Python since a few months.
But how could I start solving this problem?

My first ideas of problems I need to solve are:
- I need to check if I can move the disk that the player want to?
- I need to check if the disk can be moved to the tower the player want to?
- I need to change the list!

So have somebody a idea how I could start?

Thanks!

Is This A Good Question/Topic? 0

## Replies To: Tower of Hanoi

### #2 DK3250

• Pythonian

Reputation: 464
• Posts: 1,473
• Joined: 27-December 13

## Re: Tower of Hanoi

Posted 05 July 2018 - 06:54 AM

First of all: Welcone to DIC, I hope you will find it helpful.

So, you want to make a game. Good idea! A few questions:

Should the gane be text based (writing to the console) or graphical ?
How should the user interact with the game, keyboard?, mouse?
Have you made other games before ?
Do you have an idea about how you would structure such a game ?

Maybe this answer is not exactly what you wanted.
We very much encourage you to make a coding attempt - then the forum will help with specific questions.
Give it a try and do not hesitate to come back if you get stuck.

### #3 Sachsen31

Reputation: 0
• Posts: 4
• Joined: 05-July 18

## Re: Tower of Hanoi

Posted 05 July 2018 - 07:26 AM

Thankīs for reacting!

I want to creat a text based game on the console, I never worked with tkinter or other possible options.
For the interaction with the game I thought about keyboard input.

So for example I have the towers A, B, C and the disk 1, 2, 3, 4 so that the user can type in the numbers and letters. Like this:

```mdisk=str(raw_input("\nWhich disk do you want to move? 1,2,3 or 4?\n"))
mtower=str(raw_input("\nTo which tower do you want to move disk "+str(mdisk)+ " ? A,B or C?\n"))

```

I never made a game like this befor, so this is my first try.

### #4 astonecipher

• Senior Systems Engineer

Reputation: 2682
• Posts: 10,736
• Joined: 03-December 12

## Re: Tower of Hanoi

Posted 05 July 2018 - 08:07 AM

You can actually go easier than that. You can only move the top disk. So, the player just needs to interact with from what tower to what tower. Then on your side, is that a valid move? Does it solve the riddle?

### #5 DK3250

• Pythonian

Reputation: 464
• Posts: 1,473
• Joined: 27-December 13

## Re: Tower of Hanoi

Posted 05 July 2018 - 08:32 AM

In my view it is more logical to ask which tower to move from and which to move to.
This will 'automatically' define which disk to move: The top disk on the 'move_from' tower.

I guess you will represent the three towers as lists like the code in post #1.
The code could go like this:
```# initialization
# make all starting values

# loop
while game_not_finished:
get_input()
validate_input()
update_all_towers()
make_output()
```

In this code structure, I use four functions in the main loop and a boolean 'game_not_finished'.

Next step is to see some code from you...
Feel free to deviate from the proposed structure.

### #6 astonecipher

• Senior Systems Engineer

Reputation: 2682
• Posts: 10,736
• Joined: 03-December 12

## Re: Tower of Hanoi

Posted 05 July 2018 - 08:34 AM

I would also encourage separating concerns. If you keep the logic separate from the output, updating this to use a GUI becomes easier.

### #7 Sachsen31

Reputation: 0
• Posts: 4
• Joined: 05-July 18

## Re: Tower of Hanoi

Posted 05 July 2018 - 12:32 PM

Hy guys, thanks for your help!

astonecipher your idea was so helpful, I think I would never have guessed to just work with the top disk of each tower.

I created up until now a pretty good programm. The user can now decide from which to which tower he want to move a disk and the values of the lists are now changing correct. I just need to make some input validation and a few more things and then I already have the programm I wanted to have.

Thank you so much I appreciate that!

### #8 DK3250

• Pythonian

Reputation: 464
• Posts: 1,473
• Joined: 27-December 13

## Re: Tower of Hanoi

Posted 05 July 2018 - 12:44 PM

@Sachsen31: If you're happy, I'm happy.

It is a nice gesture to up-vote posts that you find helpful.

You might benefit from sharing your code with us; could be, you would receive suggestions for improvement...

### #9 Sachsen31

Reputation: 0
• Posts: 4
• Joined: 05-July 18

## Re: Tower of Hanoi

Posted 05 July 2018 - 01:01 PM

Okay, so thatīs my code up until now. Itīs not 100% finished yet.

There still need to make a input validation (so that the user donīt type letters or numbers higher 3), the stop of the while loop need to be rework and the check if in the finish tower is a lower value disk at the top so that the move is not possible. But still I am happy with my result for today

```def starting_tower(tower,position):
while tower[position] == 0:
position=position-1
disk=tower[position]
tower[position]=0
return disk

def finish_tower(tower,disk,position):
while tower[position] <> 0:
position=position+1
tower[position]=disk

A=[4,3,2,1]
B=[0,0,0,0]
C=[0,0,0,0]

print str(A) + str(B)/> + str(C)

while (4 and 3 and 2 and 1) not in C:

stower=str(raw_input("\nFrom which tower do you want to move the top disk? 1,2 or 3? \n"))
ztower=str(raw_input("\nTo which tower do you want to move the disk? 1,2 or 3? \n"))

if int(stower) == 1:
disk=starting_tower(A,3)
elif int(stower) == 2:
disk=starting_tower(B,3)
elif int(stower) == 3:
disk=starting_tower(C,3)

if int(ztower) == 1:
finish_tower(A,disk,0)
elif int(ztower) == 2:
finish_tower(B,disk,0)
elif int(ztower) == 3:
finish_tower(C,disk,0)

print str(A) + str(B)/> + str(C)

```

### #10 DK3250

• Pythonian

Reputation: 464
• Posts: 1,473
• Joined: 27-December 13

## Re: Tower of Hanoi

Posted 05 July 2018 - 01:25 PM

Just a quick feed-back:
Line 19 does not work the way you want it to.
You need to do
```while 4 not in C and 3 not in C and 2 not in C and 1 not in C:
```

Not very nice..!
More pythonic is
```while not all(x in C for x in (1,2,3,4)):
```

But this is still bad, - what if you tower is 10 high..?
Try to make the code independent of specific the number of discs

Why do you use Python 2 ?
If you have just started, Python 3 is probably a better choice.

This post has been edited by DK3250: 05 July 2018 - 01:33 PM
Reason for edit:: wrong syntax in all()

### #11 jon.kiparsky

• Beginner

Reputation: 11275
• Posts: 19,314
• Joined: 19-March 11

## Re: Tower of Hanoi

Posted 05 July 2018 - 01:27 PM

Looks like a good start. There are some things that you can clean up, and a few computing concepts that you could learn.
Cleanup ideas:

```def starting_tower(tower,position)
```

Why does this take a "position" argument? Isn't it always going to take the top disk from the tower?

I would consider starting_tower and finishing_tower to be an odd pair of functions. What I think you want to do here is to move_disk(source, destination).

stower and ztower are not great names, in that they don't tell me what these really mean. I would prefer source_tower and destination_tower, or something of that sort.

I would prefer to see a dict lookup instead of the chain of ifs. towers = {1: A, 2: B, 3: C} would be a reasonable intermediate change.

There are a lot of other things you can do to improve this, but like I say it's certainly not a bad start. Good stuff.

Here's one idea that's worth learning which comes out of your implementation. It's called a "stack". A stack is a data structure that offers two operations: you can put things on the stack, and you can take things off the stack. Sometimes people will add other operations, but those are the key ones. The important thing is that when you take an item off the stack, it's always the last thing that you added. So, to make it concrete, if you have a stack of plates, you can put plates on top of the stack and any time you go to take a plate, you get the one that was put on the stack most recently.
In this case, you would want to have a constraint on your stack that you can only put a smaller disk on a larger one, and not vice versa, but this should not be hard to manage.

Implementing a stack effectively in python will require that you understand the basics of objects and classes, so it might not be something you do today, but you should be able to see how this would simplify your code, for example if you had four towers instead of three, or five instead of four.
The stack concept is also very useful as you go forward in programming and computer science, as it turns out. A bit of googling will probably help you get some more ideas about it.

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }