[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] PCR: subtract rectangles



Hi,

attached is a code snippet to subtract rectangles.

Gerrit.

-- 
27. If a chieftain or man be caught in the misfortune of the king
(captured in battle), and if his fields and garden be given to another and
he take possession, if he return and reaches his place, his field and
garden shall be returned to him, he shall take it over again.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/
import pygame

def coor2rect(c):
    """Converts ((x,y),(x,y)) style coords to a Rect object"""
    topx = min(c[0][0], c[1][0])
    bottomx = max(c[0][0], c[1][0])
    topy = min(c[0][1], c[1][1])
    bottomy = max(c[0][1], c[1][1])
    size = (bottomx-topx, bottomy-topy)
    return pygame.rect.Rect([topx, topy, size[0], size[1]])

def subtractrect(outer, inner):
    """Subtract inner rectangle from outer rectangle.

    This function takes as arguments two rectangles, and
    returns a list of rectangles covering all areas covered
    by the outer rectangle but not by the inner rectangle.
    The inner rectangle must reside entirely inside the outer
    rectangle. This function always returns a list of 4 rectangles.
    If outer == inner, all rectangles have size 0. This function
    tries to distribute the uncovered area's fairly over the
    4 rectangles.

    This function uses the coor2rect() function, so that one
    is included in the same code snippet.
    """

    if not outer.contains(inner):
        raise ValueError("rect1 must contain rect2")
    coords = []
    coords.append((outer.topleft, inner.topright))
    coords.append(((inner.right, outer.top), (outer.right, inner.bottom)))
    coords.append((inner.bottomleft, outer.bottomright))
    coords.append(((outer.left, inner.top), (inner.left, outer.bottom)))
    return [coor2rect(i) for i in coords]