
李兴球Python海龟画图矩形碰撞演示
"""
矩形碰撞演示程序.py
下面的r1.gif和r2.gif是两张100x100像素的图形。
"""
__author__ = '李兴球'
__date__ = '2020/06/14'
__blog__ = 'www.lixingqiu'
from turtle import Turtle,Screen
def collide(t1,t2):
"""检测t1是否和t2重叠"""
t1_left = t1.xcor() - 50 # t1最左x坐标
t1_right = t1.xcor() + 50 # t1最右x坐标
t1_top = t1.ycor() + 50 # t1最上y坐标
t1_bottom = t1.ycor() - 50 # t1最下y坐标
t2_left = t2.xcor() - 50
t2_right = t2.xcor() + 50
t2_top = t2.ycor() + 50
t2_bottom = t2.ycor() - 50
# 以下c1,c2,c3,c4是两个矩形不重叠的情况
c1 = t1_right t2_right # t1最左x坐标大于t2最右x坐标
c3 = t1_topt2_top # t1最小y坐标大于t2最上y坐标
if c1 or c2 or c3 or c4 : # 如果4种情况,只要有一种情况发生了
return False # 那么就没有碰撞到
else: # 否则
return True # 就说明两个矩形重叠了
def motion(event):
"""鼠标移动事件"""
screen.cv.unbind("")
x = screen.cv.canvasx(event.x)/screen.xscale
y = -screen.cv.canvasy(event.y)/screen.yscale
greensquare.goto(x,y)
if collide(greensquare,bluesquare):
screen.title('碰撞中....')
else:
screen.title('矩形碰撞演示程序by lixingqiu')
screen.update()
screen.cv.bind("",motion)
width,height = 480,360
screen = Screen()
screen.setup(width,height)
screen.bgcolor('orange')
screen.addshape('r1.gif')
screen.addshape('r2.gif')
screen.title('矩形碰撞演示程序by lixingqiu')
screen.tracer(0,0)
bluesquare = Turtle(shape='r2.gif')
greensquare = Turtle(visible=False)
greensquare.penup()
greensquare.shape('r1.gif')
greensquare.st()
screen.update()
screen.cv.bind("",motion)
screen.mainloop()

李兴球Python矩形碰撞逆向思维法示意图