python运用turtle 画出汉诺塔搬运过程
1.打开 IDLE 点击File-New File 新建立一个py文件
2.向py文件中输入如下代码
1 import turtle 2 class Stack: #面向对象,定义一个类 3 def __init__(self): 4 self.items = [] 5 def isEmpty(self): 6 return len(self.items) == 0 7 def push(self, item): 8 self.items.append(item) 9 def pop(self): 10 return self.items.pop() 11 def peek(self): 12 if not self.isEmpty(): 13 return self.items[len(self.items) - 1] 14 def size(self): 15 return len(self.items) 16 def drawpole_3(): #这里是绘制三个塔柱子 17 t = turtle.Turtle() 18 t.hideturtle() 19 def drawpole_1(k): 20 t.up() 21 t.pensize(10) 22 t.speed(100) 23 t.goto(400*(k-1), 300) 24 t.down() 25 t.goto(400*(k-1), -100) 26 t.goto(400*(k-1)-20, -100) 27 t.goto(400*(k-1)+20, -100) 28 drawpole_1(0) 29 drawpole_1(1) 30 drawpole_1(2) 31 def creat_plates(n): #按照输入的n来画出盘子个数 32 plates=[turtle.Turtle() for i in range(n)] 33 for i in range(n): 34 plates[i].up() 35 plates[i].hideturtle() 36 plates[i].shape("square") 37 plates[i].shapesize(1,20-i) 38 plates[i].goto(-400,-90+20*i) 39 plates[i].showturtle() 40 return plates 41 def pole_stack(): #这里运用栈来控制一次只能搬动一个盘子并且递归 42 poles=[Stack() for i in range(3)] 43 return poles 44 def moveDisk(plates,poles,fp,tp): #搬动盘子 45 mov=poles[fp].peek() 46 plates[mov].goto((fp-1)*400,300) 47 plates[mov].goto((tp-1)*400,300) 48 l=poles[tp].size() 49 plates[mov].goto((tp-1)*400,-90+20*l) 50 def moveTower(plates,poles,height,fromPole, toPole, withPole): 51 if height >= 1: 52 moveTower(plates,poles,height-1,fromPole,withPole,toPole) 53 moveDisk(plates,poles,fromPole,toPole) 54 poles[toPole].push(poles[fromPole].pop()) 55 moveTower(plates,poles,height-1,withPole,toPole,fromPole) 56 myscreen=turtle.Screen() 57 drawpole_3() 58 n=int(input("请输入汉诺塔的层数并回车:\n")) 59 plates=creat_plates(n) 60 poles=pole_stack() 61 for i in range(n): 62 poles[0].push(i) 63 moveTower(plates,poles,n,0,2,1) 64 myscreen.exitonclick()
3. 点击 Run-Run Module 或者F5 运行程序
这个时候会出现两个窗口,在左边窗口按照提示输入,右边则是turtle的画布
4.运行 例子:在左边窗口输入3 回车
完成~~~~~~~~~~
(ps:输入的数字越大,花的时间更久,然后要防止自己的电脑cpu过载!!)
可自行输入别的数字