获取填充块的左右上下坐标

原文转载自 「李兴球的博客」 ( http://www.lixingqiu.com/2020/07/25/获取填充块的左右上下坐标/ ) By 李兴球

预计阅读时间 0 分钟(共 0 个字, 0 张图片, 0 个链接)

李兴球海龟绘图移动的正方形填充块移动
李兴球海龟绘图移动的正方形填充块移动

海龟画完红色的正方形后,再单击,在画布上的项目们都会移动.

"""
   获取填充块的左右上下坐标
   单击后移动字和海龟,填充块会移动并且碰到边缘会反弹
"""
import time
import turtle
from random import randint

turtle.shape('turtle')
turtle.penup()
turtle.speed(1)
turtle.fillcolor('red')
turtle.begin_fill()
for _ in range(4):
    turtle.fd(100)
    turtle.rt(90)
turtle.end_fill()

hg = turtle.getturtle()
sc = turtle.getscreen()
cv = turtle.getcanvas()
sw = sc.window_width()    # 屏宽
sh = sc.window_height()   # 屏高

def move(x,y):
    sc.onclick(None)
    dx = randint(-5,5)
    dy = randint(-5,5)
    while True:
        cv.move(text,1,0)
        turtle.setx(turtle.xcor()-1)
        cv.move(redsquare,dx,dy)
        cv.update()
        xy = cv.coords(redsquare)
        left = min([xy[i] for i in range(len(xy)) if i%2==0])
        right = max([xy[i] for i in range(len(xy)) if i%2==0])
        top = max([xy[i] for i in range(len(xy)) if i%2==1])
        bottom = min([xy[i] for i in range(len(xy)) if i%2==1])
        if left<= -sw//2 or right>= sw//2:dx = -dx
        if top>= sh//2 or bottom<= -sh//2:dy = -dy
        time.sleep(0.01)
        
redsquare = hg.items[-1]
zt = ('',32,'underline')
turtle.sety(turtle.ycor() + 100)
turtle.write('请单击',align='center',font=zt)
text = hg.items[-1]
sc.onclick(move)
sc.mainloop()
    

more_vert