小型汉诺塔的动画,六层塔盘从左边移动到右边。
圆盘就是一个海龟,但是形状设置成了方形。
代码解析:
from turtle import *
# 圆盘
class Disc(Turtle):
def __init__(self, n):
Turtle.__init__(self, shape="square", visible=False)
self.pu()
# 矩形大小
self.shapesize(1.5, n*1.5, 2) # square-->rectangle
# 设置颜色
self.fillcolor(n/6., 0, 1-n/6.)
self.st()
# 塔
class Tower(list):
"Hanoi tower, a subclass of built-in type list"
def __init__(self, x):
"create an empty tower. x is x-position of peg"
self.x = x
# 加入盘子
def push(self, d):
d.setx(self.x)
d.sety(-150+34*len(self))
self.append(d)
# 取出盘子
def pop(self):
d = list.pop(self)
d.sety(150)
return d
# 汉诺塔算法
def hanoi(n, from_, with_, to_):
if n > 0:
hanoi(n-1, from_, to_, with_)
to_.push(from_.pop())
hanoi(n-1, with_, from_, to_)
def play():
onkey(None,"space")
clear()
try:
hanoi(6, t1, t2, t3)
write("press STOP button to exit",
align="center", font=("Courier", 16, "bold"))
except Terminator:
pass # turtledemo user pressed STOP
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
# 放置三个塔
t1 = Tower(-250)
t2 = Tower(0)
t3 = Tower(250)
# make tower of 6 discs
# 第一个塔加六个盘子
for i in range(6,0,-1):
t1.push(Disc(i))
# prepare spartanic user interface ;-)
write("press spacebar to start game",
align="center", font=("Courier", 16, "bold"))
onkey(play, "space")
listen()
return "EVENTLOOP"
if __name__=="__main__":
msg = main()
print(msg)
mainloop()
通过修改参数很容易增加盘子数目,比如增加到20个盘子
from turtle import *
disc_num = 20
# 圆盘
class Disc(Turtle):
def __init__(self, n):
Turtle.__init__(self, shape="square", visible=False)
self.pu()
# 矩形大小
self.shapesize(1.1, n*1.1, 1.1) # square-->rectangle
# 设置颜色
self.fillcolor(n/disc_num, 0, 1-n/disc_num)
self.st()
# 塔
class Tower(list):
"Hanoi tower, a subclass of built-in type list"
def __init__(self, x):
"create an empty tower. x is x-position of peg"
self.x = x
# 加入盘子
def push(self, d):
d.setx(self.x)
d.sety(-150+20*len(self))
self.append(d)
# 取出盘子
def pop(self):
d = list.pop(self)
d.sety(150)
return d
# 汉诺塔算法
def hanoi(n, from_, with_, to_):
if n > 0:
hanoi(n-1, from_, to_, with_)
to_.push(from_.pop())
hanoi(n-1, with_, from_, to_)
def play():
onkey(None,"space")
clear()
try:
hanoi(disc_num, t1, t2, t3)
except Terminator:
pass # turtledemo user pressed STOP
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
tracer(2000)
# 放置三个塔
t1 = Tower(-550)
t2 = Tower(0)
t3 = Tower(550)
# make tower of disc_num discs
# 第一个塔加六个盘子
for i in range(disc_num,0,-1):
t1.push(Disc(i))
# prepare spartanic user interface ;-)
write("press spacebar to start game",
align="center", font=("Courier", 16, "bold"))
onkey(play, "space")
listen()
return "EVENTLOOP"
if __name__=="__main__":
msg = main()
print(msg)
mainloop()
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容