Senior's Blog

ゴルフ(Golf)、python(Pythonista)、メンタルヘルスに関するブログです。

(36)Tower of Hanoi

ハノイの塔を解くプログラムを書いてみました。

ネットで検索してたらすぐに見つかりましたので、それを参考にさせて頂きました。

7段を移動させる場合のプログラムです。

グラフィカルに表示させるのは簡単にできませんでしたので、

取り急ぎ、結果はコンソール表示するものです。

 

import ui

step = 1

def hanois(num_disk, from_twr, to_twr, tmp_twr):
    global step
    #Move disk from 'from_twr' to 'to_twr'.
    if num_disk == 1:
        #if 1disk, move it finished.
        print(f"step{step}: No.{num_disk}-disk from {from_twr} to {to_twr}.")
        step = step + 1
        return
    #Move (N-1)th. disk from Left to Center. Right as temporary tower
    hanois(num_disk-1, from_twr, tmp_twr, to_twr)
    #Move remaining disk from Left to Right
    print(f"step{step}: No.{num_disk}-disk from {from_twr} to {to_twr}.")
    step = step + 1
    #Move (N-1)th. disk from Center to Right. Left as temporary tower
    hanois(num_disk-1, tmp_twr, to_twr, from_twr) 

hanois(7, "Left", "Right", "Center")

v = ui.load_view()
v.present('sheet')

 

実行結果:

結果はコンソールに表示されます。

Ui画像は初期表示するだけで動かす処理は未実装です。

ボタンを配置してそれを動かそうとしていましたが、ちょっと簡単にいきませんでした。

f:id:SuzyLW:20200128232521j:plain