Skip to content

Commit

Permalink
__complex__
Browse files Browse the repository at this point in the history
  • Loading branch information
bilhox committed Oct 20, 2024
1 parent 8b09b1f commit 1bbf4f0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docs/reST/ref/math.rst
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,9 @@ Multiple coordinates can be set using slices or swizzling
Inherited methods of vector subclasses now correctly return an instance of the
subclass instead of the superclass

.. versionchanged:: 2.5.3
It is now possible to convert a ``Vector2`` to a complex number using ``complex()``.

.. method:: dot

| :sl:`calculates the dot- or scalar-product with the other vector`
Expand Down
14 changes: 14 additions & 0 deletions src_c/math.c
Original file line number Diff line number Diff line change
Expand Up @@ -2200,6 +2200,19 @@ vector2_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return (PyObject *)vec;
}

static PyObject *
vector2_complex(pgVector *self, PyObject *_null)
{
PyObject *complex =
PyComplex_FromDoubles(self->coords[0], self->coords[1]);

if (complex == NULL) {
RAISE(PyExc_ValueError, "Couldn't build complex number from Vector2");
}

return complex;
}

static int
_vector2_set(pgVector *self, PyObject *xOrSequence, PyObject *y)
{
Expand Down Expand Up @@ -2578,6 +2591,7 @@ static PyMethodDef vector2_methods[] = {
NULL},
{"__reduce__", (PyCFunction)vector2_reduce, METH_NOARGS, NULL},
{"__round__", (PyCFunction)vector___round__, METH_VARARGS, NULL},
{"__complex__", (PyCFunction)vector2_complex, METH_NOARGS, NULL},

{NULL} /* Sentinel */
};
Expand Down
16 changes: 16 additions & 0 deletions test/math_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,22 @@ def assign_nonfloat():

self.assertRaises(TypeError, assign_nonfloat)

def test__complex__(self):
vec1 = pygame.Vector2(23, 45)
vec2 = pygame.Vector2(-123, 4859358338)
vec3 = pygame.Vector3(-25720.733232, -9404993.45)

complex1 = complex(vec1)
complex2 = complex(vec2)
complex3 = complex(vec3)

self.assertEqual(vec1.x, complex1.real)
self.assertEqual(vec1.y, complex1.imag)
self.assertEqual(vec2.x, complex2.real)
self.assertEqual(vec2.y, complex2.imag)
self.assertAlmostEqual(vec3.x, complex3.real)
self.assertAlmostEqual(vec3.y, complex3.imag)

def test___round___basic(self):
self.assertEqual(round(pygame.Vector2(0.0, 0.0)), pygame.Vector2(0.0, 0.0))
self.assertEqual(type(round(pygame.Vector2(0.0, 0.0))), pygame.Vector2)
Expand Down

0 comments on commit 1bbf4f0

Please sign in to comment.