turtle自动扩张
问题来源
想画一个勾股树,没想到。。。(看图)
超出边界了啊喂!
setworldcoordinates
的作用
官方说明:
"""
Set up a user defined coordinate-system.
Arguments:
llx -- a number, x-coordinate of lower left corner of canvas
lly -- a number, y-coordinate of lower left corner of canvas
urx -- a number, x-coordinate of upper right corner of canvas
ury -- a number, y-coordinate of upper right corner of canvas
Set up user coodinat-system and switch to mode 'world' if necessary.
This performs a screen.reset. If mode 'world' is already active,
all drawings are redrawn according to the new coordinates.
But ATTENTION: in user-defined coordinatesystems angles may appear
distorted. (see Screen.mode())
Example (for a TurtleScreen instance named screen):
>>> screen.setworldcoordinates(-10,-0.5,50,1.5)
>>> for _ in range(36):
... left(10)
... forward(0.5)
"""
翻译成人话就是:
前两个参数是左下角的坐标,
后两个参数是右上角的坐标。
作用嘛,自己去试一试就知道了
实现1
用 4 4 4个变量记录左下角与右上角的坐标,具体实现如下:
lx=min(lx,t.pos()[0]);ly=min(ly,t.pos()[1]);hx=max(hx,t.pos()[0]);hy=max(hy,t.pos()[1])
t.setworldcoordinates(lx0,ly,hx,hy)
这段代码每一次移动都要使用(悲)
效果吗。。。
紧贴着,不好看!
实现2
lx=min(lx,t.pos()[0]);ly=min(ly,t.pos()[1]);hx=max(hx,t.pos()[0]);hy=max(hy,t.pos()[1])
t.setworldcoordinates(lx-10,ly-10,hx+10,hy+10)
效果:
这回有 “边框” 了
顺便送上勾股树的源代码:
width=numinput("输入边长","输入窗口边长(像素)")
root=TK.Tk();root2=TK.Canvas(root,width=width+20,height=width+20);root2.pack()
scr=TurtleScreen(root2)
p=RawTurtle(scr,"turtle")
scr.setworldcoordinates(-10,-10,width+10,width+10)
root.title("勾股树")
p.pu();p.goto(0,0);p.pd()
for i in range(4):
p.fd(width);p.lt(90)
depth=int(numinput("输入层数",'输入勾股树迭代层数(必须是整数)'))
angle=numinput("角度","输入角度(0-180)")
scr.tracer(40)
global lx,ly,hx,hy
lx=0;ly=0;hx=width;hy=width
print(lx,ly,hx,hy)
def tree(ln,mode="left",h=90,p1=(0,0),d=0):
p.pu()
p.seth(h)
p.goto(p1)
if d<depth and ln>1:
p.pd()
for i in range(4):
if i==1 and mode=="left":
pos1=p.pos()
if i==2 and mode=="left":
pos2=p.pos()
if i==2 and mode=="right":
pos1=p.pos()
if i==3 and mode=="right":
pos2=p.pos()
p.fd(ln)
p.right(90)
global lx,ly,hx,hy
lx=min(lx,p.pos()[0]);ly=min(ly,p.pos()[1]);hx=max(hx,p.pos()[0]);hy=max(hy,p.pos()[1])
scr.setworldcoordinates(lx-30,ly-30,hx+30,hy+30)
h=p.heading()
tree(ln*math.cos(math.radians(angle)),"left",h+angle if mode=="left" else h-angle,pos1,d+1)
tree(ln*math.cos(math.radians((90-angle))),"right",h+angle if mode=="left" else h-(90-angle),pos2,d+1)
scr.setworldcoordinates(-width-10,-10,2*width+10,3*width+10)
tree(width)
TK.mainloop()
莫抄袭,因为有省略,运行不起来。