python2.6版本中後引入的乙個簡單的繪圖工具,叫做海龜繪圖(turtle graphics),turtle庫是python的內部庫。
turtle庫
漢諾塔
import turtle
defdraw_post()
:'''畫三個柱子'''
h.speed(0)
h.up(
) h.left(90)
h.pensize(
10)
d(-350,-
200)
d(0,
-200
) d(
350,
-200
)def
d(x,y)
:'''畫乙個柱子'''
h.goto(x,y)
h.down(
) h.fd(
300)
h.up(
)def
draw()
:'''依次繪製圓盤至a上面'''
for index,t in
enumerate
(a[1])
: t.goto(a[0]
[index][0
],a[0]
[index][1
])a_line(t)
defa_line
(t):
'''畫乙個側視圓盤'''
t.speed(0)
t.down(
) t.fd(t.width)
t.back(
2*t.width)
t.up(
)def
prepare_pen()
:for x in
range
(num,0,
-1):
t = turtle.turtle(
) t.up(
) t.ht(
) t.speed(0)
t.pensize(high)
t.width = x*
20 t.color(color[x-1]
) a[1]
defm
(n,a,b,c)
:'''遞迴實現漢諾塔'''
if n ==1:
a[1]
[-1]
.speed(speed)
a[1]
[-1]
.goto(c[0]
[c[2]]
[0],c[0]
[c[2]]
[1])
a[1]
[-1]
.clear(
) a_line(a[1]
[-1]
) ob = a[1]
.pop(
) a[2]
=len
(a[1])
c[1]
c[2]
=len
(c[1])
return
else
: m(n-
1,a,c,b)
m(1,a,b,c)
m(n-
1,b,a,c)
if __name__ ==
"__main__"
:#turtle.tracer(0,0)
# 畫布大小
turtle.setup(
1000
,700
)# 每個餅的高度
high =
40# 餅的數量,受顏色限制,最多7個
num =
5# 速度 0 最快 0-10 遞增
speed =
10# 餅的顏色
color =
["red"
,"green"
,"pink"
,"blue"
,"purple"
,"black"
,"yellow"
]# 三個存放餅相關資料的列表,[[座標],[餅],最新的放置索引]
a =[[
[-350,
-200
+x*high]
for x in
range
(num)],
,6] b =[[
[0,-
200+x*high]
for x in
range
(num)],
,0] c =[[
[350,-
200+x*high]
for x in
range
(num)],
,0]# 準備所有的餅
prepare_pen(
)# 畫三個柱子
h = turtle.turtle(
) draw_post(
)# 餅的初始化
draw(
)# 遞迴實現漢諾塔
m(num,a,b,c)
turtle.done(
)
import turtle
defprepare_pen()
:'''準備繪製漢諾塔的畫筆'''
for i in
range
(num,0,
-1):
t = turtle.turtle(
) t.speed(5)
t.up(
) t.ht(
) t.n = i
t.size =
(i+1)*
40 t.color(color[i-1]
) a[0]
definit()
:'''初始化漢諾塔'''
for p in a[0]
: p.goto(a[1]
[0], a[1]
[1])
p.dot(p.size)
p.write(p.n)
defwrite_symbol()
:'''繪製三個位置符號'''
p =[a,b,c]
h = turtle.turtle(
) h.ht(
) h.speed(0)
for u in p:
h.up(
) h.goto(u[1]
[0],u[1]
[1])
h.write(u[2]
,font=
("楷體",30
))defm
(n,a,b,c)
:'''遞迴實現漢諾塔'''
if n ==1:
a[0]
[-1]
.goto(c[1]
[0],c[1]
[1])
a[0]
[-1]
.clear(
) a[0]
[-1]
.dot(a[0]
[-1]
.size)
a[0]
[-1]
.write(a[0]
[-1]
.n) ob = a[0]
.pop(
) c[0]
return
else
: m(n-
1,a,c,b)
# 手電需要吧(n-1)個圓盤移動到 b
m(1,a,b,c)
# 將a的最後乙個圓盤一定到 c
m(n-
1,b,a,c)
# 在將b的(n-1)個圓盤移動到 c
if __name__ ==
"__main__"
:# 準備三個位置的資訊列表[[餅],座標,符號]
a =[[
],[-
100,
100]
,"a"
] b =[[
],[-
50,-200],
"b"]
c =[[
],[200,0
],"c"]
# 餅的顏色
color =
["red"
,"green"
,"pink"
,"blue"
,"purple"
,"black"
,"yellow"
]# 繪製三個位置符號
write_symbol(
)# 餅的數量
num =
7# 準備餅
prepare_pen(
)# 餅的初始化
init(
)# 遞迴實現漢諾塔
m(num,a,b,c)
turtle.done(
)
turtle庫實現漢諾塔
import turtle turtle.screensize 800,800 class stack def init self self.items def isempty self return len self.items 0 def push self,item def pop self ...
用Python完成漢諾塔
steps 0 計算步數,一共移動幾次完成 def hanoi src,mid,des,n 這個函式接收 三個柱子和圓盤個數n global steps 將 作為全域性變數 if n 1 如果圓盤只有乙個的話一部就完成了 steps 1 print step format steps,src,des...
python 漢諾塔 Python漢諾塔
import turtle class stack def init self self.items def isempty self return len self.items 0 def push self,item def pop self return self.items.pop def ...