feat: Add Entity.die() method for lifecycle management closes #30

- Remove entity from its grid's entity list
- Clear grid reference after removal
- Safe to call multiple times (no-op if not on grid)
- Works with shared_ptr entity management
This commit is contained in:
John McCardle 2025-07-06 00:45:01 -04:00
commit fe5976c425
2 changed files with 29 additions and 0 deletions

View file

@ -1,6 +1,7 @@
#include "UIEntity.h"
#include "UIGrid.h"
#include "McRFPy_API.h"
#include <algorithm>
#include "PyObjectUtils.h"
#include "PyVector.h"
@ -323,9 +324,36 @@ int UIEntity::set_float_member(PyUIEntityObject* self, PyObject* value, void* cl
return 0;
}
PyObject* UIEntity::die(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored))
{
// Check if entity has a grid
if (!self->data || !self->data->grid) {
Py_RETURN_NONE; // Entity not on a grid, nothing to do
}
// Remove entity from grid's entity list
auto grid = self->data->grid;
auto& entities = grid->entities;
// Find and remove this entity from the list
auto it = std::find_if(entities->begin(), entities->end(),
[self](const std::shared_ptr<UIEntity>& e) {
return e.get() == self->data.get();
});
if (it != entities->end()) {
entities->erase(it);
// Clear the grid reference
self->data->grid.reset();
}
Py_RETURN_NONE;
}
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"},
{"die", (PyCFunction)UIEntity::die, METH_NOARGS, "Remove this entity from its grid"},
{NULL, NULL, 0, NULL}
};