Implement Entity.index() method for Issue #73

Added index() method to Entity class that returns the entity's
position in its parent grid's entity collection. This enables
proper entity removal patterns using entity.index().
This commit is contained in:
John McCardle 2025-07-03 21:02:14 -04:00
commit 923350137d
6 changed files with 234 additions and 5 deletions

View file

@ -36,6 +36,33 @@ PyObject* UIEntity::at(PyUIEntityObject* self, PyObject* o) {
}
PyObject* UIEntity::index(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored)) {
// Check if entity has an associated grid
if (!self->data || !self->data->grid) {
PyErr_SetString(PyExc_RuntimeError, "Entity is not associated with a grid");
return NULL;
}
// Get the grid's entity collection
auto entities = self->data->grid->entities;
if (!entities) {
PyErr_SetString(PyExc_RuntimeError, "Grid has no entity collection");
return NULL;
}
// Find this entity in the collection
int index = 0;
for (auto it = entities->begin(); it != entities->end(); ++it, ++index) {
if (it->get() == self->data.get()) {
return PyLong_FromLong(index);
}
}
// Entity not found in its grid's collection
PyErr_SetString(PyExc_ValueError, "Entity not found in its grid's entity collection");
return NULL;
}
int UIEntity::init(PyUIEntityObject* self, PyObject* args, PyObject* kwds) {
//static const char* keywords[] = { "x", "y", "texture", "sprite_index", "grid", nullptr };
//float x = 0.0f, y = 0.0f, scale = 1.0f;
@ -211,6 +238,7 @@ int UIEntity::set_spritenumber(PyUIEntityObject* self, PyObject* value, void* cl
PyMethodDef UIEntity::methods[] = {
{"at", (PyCFunction)UIEntity::at, METH_O},
{"index", (PyCFunction)UIEntity::index, METH_NOARGS, "Return the index of this entity in its grid's entity collection"},
{NULL, NULL, 0, NULL}
};

View file

@ -47,6 +47,7 @@ public:
UIEntity(UIGrid&);
static PyObject* at(PyUIEntityObject* self, PyObject* o);
static PyObject* index(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored));
static int init(PyUIEntityObject* self, PyObject* args, PyObject* kwds);
static PyObject* get_position(PyUIEntityObject* self, void* closure);