python 游戏 —— 汉诺塔(Hanoita)
一.非可视化代码
def printf(A,C): #盘子移动的输出格式
print("{} --> {}".format(A,C))
def move(n,A,B,C):
if n == 1:
printf(A,C) #将最后1个盘子从A座移到C座
else:
move(n-1,A,C,B) #将n个盘子从A座借助B座移到C座
printf(A,C) #将最后1个盘子从A座移到C座
move(n-1,B,A,C) #将n个盘子从B座借助A座移到C座
N = int(input("请输入汉诺塔层数:"))
move(N,'A','B','C')
编译结果:
二.可视化代码
from turtle import *
class 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_1(k):#画汉诺塔的底座
up()
pensize(10)
speed(100)
goto(400*(k-1), 100)
down()
goto(400*(k-1), -100)
goto(400*(k-1)-20, -100)
goto(400*(k-1)+20, -100)
def drawpole_3():#画出汉诺塔的三个底座
hideturtle()#隐藏
drawpole_1(0)#画出汉诺塔的底座左
drawpole_1(1)#画出汉诺塔的底座中
drawpole_1(2)#画出汉诺塔的底座右
def creat_plates(n):#制造n个盘子
plates=[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 plates
def pole_stack():#制造底座的栈
poles=[Stack() for i in range(3)]
return poles
def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子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()#确定移动到底部的高度(恰好放在原来最上面的盘子上面)
plates[mov].goto((tp-1)*400,-90+20*l)
def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子
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=Screen()
setup(1200,500) #设置窗口大小
drawpole_3() #画汉诺塔的底座
n=int(input("请输入汉诺塔的层数并回车:"))#输入汉诺塔的盘子数
plates=creat_plates(n)#制造n个盘子
poles=pole_stack()
for i in range(n):
poles[0].push(i)
moveTower(plates,poles,n,0,2,1)
myscreen.exitonclick()
编译结果: