如何在graphics.py中检查两个框之间的冲突



如何使用John Zelle的graphics.py模块检查两个盒子之间的碰撞?

编辑:

我找到了一种方法,可以找到任何两个具有x,y,宽度,高度的类之间的碰撞。它有点乱,但它能完成任务:

def collided(self, collider):
if self.x < collider.x + collider.width and
self.x + self.width > collider.x and
self.y < collider.y + collider.height and
self.y + self.height > collider.y:
return True
return False

如果有人有更好的方法,我们将不胜感激!

这里有一个小演示程序,演示了一种相当简洁的方法——它包含一个名为intersect()的函数,用于检查graphics模块的Rectangle类的两个实例是否相交。

这样做的一个稍微棘手的方面是,用于定义Rectangle的两个Point不需要是其右下角和左上角,这是intersect()函数中的逻辑所要求的。为了处理这个问题,使用了一个名为canonical_rect()的辅助函数,使它传递的每个参数都是这样。

from graphics import *
from random import randint

WIDTH, HEIGHT = 640, 480
def rand_point():
""" Create random Point within window's limits. """
return Point(randint(0, WIDTH), randint(0, HEIGHT))
def rand_rect():
""" Create random Rectangle within window's limits. """
p1, p2 = rand_point(), rand_point()
while p1 == p2:  # Make sure points are different.
p2 = rand_point()
return Rectangle(p1, p2)
def canonical_rect(rect):
""" Return new Rectangle whose points are its lower-left and upper-right
extrema - something Zelle graphics doesn't require.
"""
p1, p2 = rect.p1, rect.p2
minx = min(p1.x, p2.x)
miny = min(p1.y, p2.y)
maxx = max(p1.x, p2.x)
maxy = max(p1.y, p2.y)
return Rectangle(Point(minx, miny), Point(maxx, maxy))
def intersect(rect1, rect2):
""" Determine whether the two arbitrary Rectangles intersect. """
# Ensure pt 1 is lower-left and pt 2 is upper-right of each rect.
r1, r2 = canonical_rect(rect1), canonical_rect(rect2)
return (r1.p1.x <= r2.p2.x and r1.p2.x >= r2.p1.x and
r1.p1.y <= r2.p2.y and r1.p2.y >= r2.p1.y)
def main():
# Initialize.
win = GraphWin('Box Collision', WIDTH, HEIGHT, autoflush=False)
center_pt = Point(WIDTH // 2, HEIGHT // 2)
box1 = Rectangle(Point(0, 0), Point(0, 0))
box2 = Rectangle(Point(0, 0), Point(0, 0))
msg = Text(center_pt, "")
# Repeat until user closes window.
while True:
box1.undraw()
box1 = rand_rect()
box1.draw(win)
box2.undraw()
box2 = rand_rect()
box2.draw(win)
if intersect(box1, box2):
text, color = "Collided", "red"
else:
text, color = "Missed", "green"
msg.undraw()
msg.setText(text)
msg.setTextColor(color)
msg.draw(win)
win.update()
try:
win.getMouse()  # Pause to view result.
except GraphicsError:
break  # User closed window.
if __name__ == '__main__':
main()

相关内容

  • 没有找到相关文章

最新更新