# 趣味正方形

## 如本文章标有价格,需议价或其它事情商议请加微信scratch8

```"""
趣味正方形.py
画个正方形后,单击它会移动,并且碰到边缘就反弹。
这个版本采用画布的move命令来当前线条项目实现的。
也可以用纯动画原理实现，还能用自定义造型来实现。
"""
import time
import turtle

sw,sh = 480,360
turtle.shape('turtle')
turtle.bgcolor('black')
turtle.color('yellow')
turtle.pensize(2)
turtle.setup(sw,sh)
for _ in range(4):
turtle.fd(50)
turtle.lt(90)

square = turtle.getturtle().currentLineItem
canvas = turtle.getcanvas()
turtle.color('cyan')
turtle.write('请单击',align='center',font=('',16,'underline'))

def gogogo(event):
turtle.ht()
dx = 5
dy = 5
canvas.unbind("")
while True:
canvas.move(square,dx,dy)
cors =  canvas.coords(square)
xcors = [cors[i] for i in range(len(cors)) if i%2==0]
ycors = [cors[i] for i in range(len(cors)) if i%2==1]
min_x = min(xcors)
max_x = max(xcors)
min_y = min(ycors)
max_y = max(ycors)
#print(min_x,max_x,min_y,max_y)
if max_x >= sw//2 or min_x <= -sw//2:dx = -dx
if max_y >= sh//2 or min_y <= -sh//2:dy = -dy
time.sleep(0.01)
canvas.update()

canvas.bind("",gogogo)

screen = turtle.getscreen()
screen.mainloop()

```

scratch