python繪制漢諾塔
本文實(shí)例為大家分享了python繪制漢諾塔的具體代碼,供大家參考,具體內(nèi)容如下
源碼:
import turtleclass Stack: def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if not self.isEmpty(): return self.items[len(self.items) - 1] def size(self): return len(self.items)def drawpole_3(): # 畫(huà)出漢諾塔的poles t = turtle.Turtle() t.hideturtle() def drawpole_1(k): t.up() t.pensize(10) t.speed(100) t.goto(400 * (k - 1), 100) t.down() t.goto(400 * (k - 1), -100) t.goto(400 * (k - 1) - 20, -100) t.goto(400 * (k - 1) + 20, -100) drawpole_1(0) # 畫(huà)出漢諾塔的poles[0] drawpole_1(1) # 畫(huà)出漢諾塔的poles[1] drawpole_1(2) # 畫(huà)出漢諾塔的poles[2]def creat_plates(n): # 制造n個(gè)盤(pán)子 plates = [turtle.Turtle() for i in range(n)] for i in range(n): plates[i].up() plates[i].hideturtle() plates[i].shape('square') plates[i].shapesize(1, 8 - i) plates[i].goto(-400, -90 + 20 * i) plates[i].showturtle() return platesdef pole_stack(): # 制造poles的棧 poles = [Stack() for i in range(3)] return polesdef moveDisk(plates, poles, fp, tp): # 把poles[fp]頂端的盤(pán)子plates[mov]從poles[fp]移到poles[tp] mov = poles[fp].peek() plates[mov].goto((fp - 1) * 400, 150) plates[mov].goto((tp - 1) * 400, 150) l = poles[tp].size() # 確定移動(dòng)到底部的高度(恰好放在原來(lái)最上面的盤(pán)子上面) plates[mov].goto((tp - 1) * 400, -90 + 20 * l)def moveTower(plates, poles, height, fromPole, toPole, withPole): # 遞歸放盤(pán)子 if height >= 1: moveTower(plates, poles, height - 1, fromPole, withPole, toPole) moveDisk(plates, poles, fromPole, toPole) poles[toPole].push(poles[fromPole].pop()) moveTower(plates, poles, height - 1, withPole, toPole, fromPole)myscreen = turtle.Screen()drawpole_3()n = int(input('請(qǐng)輸入漢諾塔的層數(shù)并回車:n'))plates = creat_plates(n)poles = pole_stack()for i in range(n): poles[0].push(i)moveTower(plates, poles, n, 0, 2, 1)myscreen.exitonclick()
效果圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼2. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼3. ASP常用日期格式化函數(shù) FormatDate()4. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. python 如何在 Matplotlib 中繪制垂直線9. jsp文件下載功能實(shí)現(xiàn)代碼10. 開(kāi)發(fā)效率翻倍的Web API使用技巧
