towers-of-hanoi/main.py
2024-10-18 20:48:09 +02:00

79 lines
2.4 KiB
Python

class TowersOfHanoiGame():
def __init__(self, n):
self.n = n
self.towers = [list(range(n-1, -1, -1)), [], []]
self.print_state()
self.moves = 0 # Counter of moves used to solve the puzle
def print_state(self):
print('-'*7)
for i in range(n-1, -1, -1):
for tower in self.towers:
try:
print(tower[i], end='')
except IndexError:
print('#', end='') # Blank space instead of tower piece
print(" ", end='') # Separate the towers
print() # New row
print('-'*7)
def move(self, t1i, t2i):
t1 = self.towers[t1i]
t2 = self.towers[t2i]
if t1 != [] and (t2 == [] or t1[-1] < t2[-1]):
self.moves += 1
print(
f"🟦 Move {self.moves}: Disk ({t1[-1]}) on tower {t1i} to tower {t2i}")
t2.append(t1.pop())
else:
print(
f"❗ Illegal move, tried to move the disk on tower {t1i} to tower {t2i}")
return False
return True
def check_win(self):
if len(self.towers[1]) == self.n or len(self.towers[2]) == self.n:
print(f"🎉 You won in {self.moves} moves!!")
if (self.moves == 2**self.n-1):
print(f"🤩 And that was the best possible solution!!")
else:
print(f"😔 But that was not the best possible solution :(")
return True
return False
def solve_game(game, n, src, dest, aux):
if n == 1:
game.move(src, dest)
game.print_state()
return
solve_game(game, n-1, src, aux, dest)
game.move(src, dest)
game.print_state()
solve_game(game, n-1, aux, dest, src)
if __name__ == "__main__":
n = int(input("❔ Number of disks in the game: "))
game = TowersOfHanoiGame(n)
what_to_do = input("❔ Play yourself (p) or let the bot solve it (b)?: ")
if what_to_do == 'p':
while True:
t1i, t2i = [int(i) for i in input(
"❔ Enter your move (tower1<space>tower2): ").split()]
game.move(t1i, t2i)
game.print_state()
if game.check_win():
break
elif what_to_do == 'b':
solve_game(game, n, 0, 1, 2)
game.check_win()
else:
print("❗ Incorrect option")