Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Circle collideswith() #2661

Merged
merged 8 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions buildconfig/stubs/pygame/geometry.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ from typing import (
)

from ._common import Coordinate, RectValue
from .rect import Rect, FRect
from .math import Vector2

_CanBeCircle = Union[Circle, Tuple[Coordinate, float], Sequence[float]]

Expand All @@ -17,6 +19,7 @@ class _HasCirclettribute(Protocol):
circle: Union[_CanBeCircle, Callable[[], _CanBeCircle]]

_CircleValue = Union[_CanBeCircle, _HasCirclettribute]
_CanBeCollided = Union[Circle, Rect, FRect, Coordinate, Vector2]
itzpr3d4t0r marked this conversation as resolved.
Show resolved Hide resolved

class Circle:
@property
Expand Down Expand Up @@ -89,6 +92,7 @@ class Circle:
def colliderect(self, x: float, y: float, w: float, h: float) -> bool: ...
@overload
def colliderect(self, topleft: Coordinate, size: Coordinate) -> bool: ...
def collideswith(self, other: _CanBeCollided) -> bool: ...
itzpr3d4t0r marked this conversation as resolved.
Show resolved Hide resolved
@overload
def update(self, circle: _CircleValue) -> None: ...
@overload
Expand Down
20 changes: 20 additions & 0 deletions docs/reST/ref/geometry.rst
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,26 @@

.. ## Circle.colliderect ##

.. method:: collideswith

| :sl:`check if a shape or point collides with the circle`
| :sg:`collideswith(Circle) -> bool`
| :sg:`collideswith(Rect) -> bool`
| :sg:`collideswith(FRect) -> bool`
| :sg:`collideswith((x, y)) -> bool`
| :sg:`contains(Vector2) -> bool`
itzpr3d4t0r marked this conversation as resolved.
Show resolved Hide resolved

The `collideswith` method checks if a shape or point overlaps with a `Circle` object.
It takes a single argument which can be a `Circle`, `Rect`, `FRect`, or a point.
It returns `True` if there's an overlap, and `False` otherwise.

.. note::
The shape argument must be an actual shape object (`Circle`, `Rect`, or `FRect`).
You can't pass a tuple or list of coordinates representing the shape (except for a point),
because the shape type can't be determined from the coordinates alone.

.. ## Circle.collideswith ##

.. method:: update

| :sl:`updates the circle position and radius`
Expand Down
40 changes: 40 additions & 0 deletions src_c/circle.c
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,44 @@ pg_circle_colliderect(pgCircleObject *self, PyObject *const *args,
return PyBool_FromLong(pgCollision_RectCircle(x, y, w, h, &self->circle));
}

static PyObject *
pg_circle_collideswith(pgCircleObject *self, PyObject *arg)
{
int result = 0;
pgCircleBase *scirc = &self->circle;
if (pgCircle_Check(arg)) {
result = pgCollision_CircleCircle(&pgCircle_AsCircle(arg), scirc);
}
else if (pgRect_Check(arg)) {
SDL_Rect *argrect = &pgRect_AsRect(arg);
result = pgCollision_RectCircle((double)argrect->x, (double)argrect->y,
(double)argrect->w, (double)argrect->h,
scirc);
}
else if (pgFRect_Check(arg)) {
SDL_FRect *argrect = &pgFRect_AsRect(arg);
result = pgCollision_RectCircle((double)argrect->x, (double)argrect->y,
(double)argrect->w, (double)argrect->h,
scirc);
}
else if (PySequence_Check(arg)) {
double x, y;
if (!pg_TwoDoublesFromObj(arg, &x, &y)) {
return RAISE(
PyExc_TypeError,
"Invalid point argument, must be a sequence of 2 numbers");
}
result = pgCollision_CirclePoint(scirc, x, y);
}
else {
return RAISE(PyExc_TypeError,
"Invalid shape argument, must be a CircleType, RectType, "
"LineType, PolygonType or a sequence of 2 numbers");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know about this one, because the argument is an instance of those types not a type itself.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I changed it a bit. I've removed mentions of Line and Poly as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure Coordinate should've been used instead of a sequence of two points since we don't really have a Coordinate object, it only appears in type stubs, maybe you can change that back, as for the other shapes, maybe those could stay in the message since otherwise they'd have to be added later and that could be forgotten.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright.

}

return PyBool_FromLong(result);
}

static struct PyMethodDef pg_circle_methods[] = {
{"collidepoint", (PyCFunction)pg_circle_collidepoint, METH_FASTCALL,
DOC_CIRCLE_COLLIDEPOINT},
Expand All @@ -400,6 +438,8 @@ static struct PyMethodDef pg_circle_methods[] = {
DOC_CIRCLE_COLLIDERECT},
{"update", (PyCFunction)pg_circle_update, METH_FASTCALL,
DOC_CIRCLE_UPDATE},
{"collideswith", (PyCFunction)pg_circle_collideswith, METH_O,
DOC_CIRCLE_COLLIDESWITH},
{"__copy__", (PyCFunction)pg_circle_copy, METH_NOARGS, DOC_CIRCLE_COPY},
{"copy", (PyCFunction)pg_circle_copy, METH_NOARGS, DOC_CIRCLE_COPY},
{NULL, NULL, 0, NULL}};
Expand Down
1 change: 1 addition & 0 deletions src_c/doc/geometry_doc.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@
#define DOC_CIRCLE_MOVE "move((x, y)) -> Circle\nmove(x, y) -> Circle\nmove(Vector2) -> Circle\nmoves the circle by a given amount"
#define DOC_CIRCLE_MOVEIP "move_ip((x, y)) -> None\nmove_ip(x, y) -> None\nmove_ip(Vector2) -> None\nmoves the circle by a given amount, in place"
#define DOC_CIRCLE_COLLIDERECT "colliderect(Rect) -> bool\ncolliderect((x, y, width, height)) -> bool\ncolliderect(x, y, width, height) -> bool\ncolliderect((x, y), (width, height)) -> bool\nchecks if a rectangle intersects the circle"
#define DOC_CIRCLE_COLLIDESWITH "collideswith(Circle) -> bool\ncollideswith(Rect) -> bool\ncollideswith(FRect) -> bool\ncollideswith((x, y)) -> bool\ncontains(Vector2) -> bool\ncheck if a shape or point collides with the circle"
#define DOC_CIRCLE_UPDATE "update((x, y), radius) -> None\nupdate(x, y, radius) -> None\nupdates the circle position and radius"
#define DOC_CIRCLE_COPY "copy() -> Circle\nreturns a copy of the circle"
52 changes: 52 additions & 0 deletions test/geometry_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,58 @@ def test_colliderect(self):
self.assertTrue(c3.colliderect(0.4, 0.0, 1, 1), msgt)
self.assertTrue(c3.colliderect((0.4, 0.0), (1, 1)), msgt)

def test_collideswith_argtype(self):
"""tests if the function correctly handles incorrect types as parameters"""
itzpr3d4t0r marked this conversation as resolved.
Show resolved Hide resolved

invalid_types = (None, [], "1", (1,), Vector3(1, 1, 1), 1)

c = Circle(10, 10, 4)

for value in invalid_types:
with self.assertRaises(TypeError):
c.collideswith(value)

def test_collideswith_argnum(self):
c = Circle(10, 10, 4)
args = [tuple(range(x)) for x in range(2, 4)]

# no params
with self.assertRaises(TypeError):
c.collideswith()

# too many params
for arg in args:
with self.assertRaises(TypeError):
c.collideswith(*arg)

def test_collideswith(self):
"""Ensures the collideswith function correctly registers collisions with circles, lines, rects and points"""
c = Circle(0, 0, 5)

# circle
c2 = Circle(0, 10, 15)
c3 = Circle(100, 100, 1)
self.assertTrue(c.collideswith(c2))
self.assertFalse(c.collideswith(c3))

# rect
r = Rect(0, 0, 10, 10)
r2 = Rect(50, 0, 10, 10)
self.assertTrue(c.collideswith(r))
self.assertFalse(c.collideswith(r2))

# rect
r = FRect(0, 0, 10, 10)
r2 = FRect(50, 0, 10, 10)
self.assertTrue(c.collideswith(r))
self.assertFalse(c.collideswith(r2))

# point
p = (0, 0)
p2 = (50, 0)
self.assertTrue(c.collideswith(p))
self.assertFalse(c.collideswith(p2))

def test_update(self):
"""Ensures that updating the circle position
and dimension correctly updates position and dimension"""
Expand Down
Loading