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

2024-09-27 21:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用John Zelle的graphics.py模块检查两个框之间的冲突

编辑:

我已经找到了一种方法来找到任意两个类之间的碰撞,它们有x,y,width,height。虽然有点凌乱,但它确实起到了作用:

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

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


Tags: 模块and方法pyself编辑returndef
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:43

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

这样做有点棘手,因为用于定义Rectangle的两个Point不需要是它的右下角和左上角,intersect()函数中的逻辑需要这两个角。为了处理这个问题,使用一个名为canonical_rect()的helper函数使它传递的每个参数都是这样

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()

相关问题 更多 >

    热门问题