Created
October 25, 2011 10:31
-
-
Save carlopires/1312209 to your computer and use it in GitHub Desktop.
Hanoi Towers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Created on 25/10/2011 | |
@author: Carlo Pires <[email protected]> | |
""" | |
class Disco: | |
def __init__(self, tamanho): | |
self.tamanho = tamanho | |
self.torre = None | |
def __unicode__(self): | |
return ('==' * self.tamanho).center(20, ' ') | |
class Torre: | |
def __init__(self): | |
self.haste = [] | |
def insere_disco(self, disco): | |
self.haste.insert(0, disco) | |
disco.torre = self | |
def remove_disco(self, disco): | |
self.haste.remove(disco) | |
class Hanoi: | |
def inicializa_torres(self): | |
self.torre1 = Torre() | |
self.torre2 = Torre() | |
self.torre3 = Torre() | |
self.torre1.insere_disco(Disco(3)) | |
self.torre1.insere_disco(Disco(2)) | |
self.torre1.insere_disco(Disco(1)) | |
def visualiza(self): | |
print "TORRE1:" | |
for disco in self.torre1.haste: | |
print unicode(disco) | |
print "TORRE2:" | |
for disco in self.torre2.haste: | |
print unicode(disco) | |
print "TORRE3:" | |
for disco in self.torre3.haste: | |
print unicode(disco) | |
def pega_disco(self, tamanho): | |
# procura na haste da torre 1 | |
for disco in self.torre1.haste: | |
if disco.tamanho == tamanho: | |
return disco | |
for disco in self.torre2.haste: | |
if disco.tamanho == tamanho: | |
return disco | |
for disco in self.torre3.haste: | |
if disco.tamanho == tamanho: | |
return disco | |
def pega_torre(self, numero): | |
if numero == 1: | |
return self.torre1 | |
elif numero == 2: | |
return self.torre2 | |
elif numero == 3: | |
return self.torre3 | |
def move_disco(self, disco, torre): | |
torre_origem = disco.torre | |
torre_origem.remove_disco(disco) | |
torre.insere_disco(disco) | |
h = Hanoi() | |
h.inicializa_torres() | |
while True: | |
print "m = movimenta disco, v = visualiza, x = sair" | |
cmd = raw_input() | |
if cmd == 'x': | |
break | |
elif cmd == 'v': | |
h.visualiza() | |
elif cmd == 'm': | |
print "Informe o disco a ser movido e a torre destino: " | |
disco, torre = map(int, raw_input().split()) | |
d = h.pega_disco(disco) | |
t = h.pega_torre(torre) | |
if d and t: | |
h.move_disco(d, t) | |
h.visualiza() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment