#!/usr/bin/env python3 """ Test for Issue #73: Entity.index() method for removal Verifies that Entity objects can report their index in the grid's entity collection. """ def test_entity_index(timer_name): """Test that Entity.index() method works correctly""" import mcrfpy import sys print("Issue #73 test: Entity.index() method") # Create test scene and grid mcrfpy.createScene("test") ui = mcrfpy.sceneUI("test") # Create grid with texture texture = mcrfpy.Texture("assets/kenney_ice.png", 16, 16) grid = mcrfpy.Grid(10, 10, texture, (10, 10), (400, 400)) ui.append(grid) # Create multiple entities entities = [] for i in range(5): entity = mcrfpy.Entity((i, i), texture, i, grid) entities.append(entity) grid.entities.append(entity) print(f"✓ Created {len(entities)} entities") # Test 1: Check each entity knows its index for expected_idx, entity in enumerate(entities): try: actual_idx = entity.index() assert actual_idx == expected_idx, f"Expected index {expected_idx}, got {actual_idx}" print(f"✓ Entity {expected_idx} correctly reports index {actual_idx}") except Exception as e: print(f"✗ Entity {expected_idx} index() failed: {e}") raise # Test 2: Remove entity using index entity_to_remove = entities[2] remove_idx = entity_to_remove.index() grid.entities.remove(remove_idx) print(f"✓ Removed entity at index {remove_idx}") # Test 3: Verify indices updated after removal for i, entity in enumerate(entities): if i == 2: # This entity was removed, should raise error try: idx = entity.index() print(f"✗ Removed entity still reports index {idx}") except ValueError as e: print(f"✓ Removed entity correctly raises error: {e}") elif i < 2: # These entities should keep their indices idx = entity.index() assert idx == i, f"Entity before removal has wrong index: {idx}" else: # These entities should have shifted down by 1 idx = entity.index() assert idx == i - 1, f"Entity after removal has wrong index: {idx}" # Test 4: Entity without grid orphan_entity = mcrfpy.Entity((0, 0), texture, 0, None) try: idx = orphan_entity.index() print(f"✗ Orphan entity should raise error but returned {idx}") except RuntimeError as e: print(f"✓ Orphan entity correctly raises error: {e}") # Test 5: Use index() in practical removal pattern # Add some new entities for i in range(3): entity = mcrfpy.Entity((7+i, 7+i), texture, 10+i, grid) grid.entities.append(entity) # Remove entities with sprite_number > 10 removed_count = 0 i = 0 while i < len(grid.entities): entity = grid.entities[i] if entity.sprite_number > 10: grid.entities.remove(entity.index()) removed_count += 1 # Don't increment i, as entities shifted down else: i += 1 print(f"✓ Removed {removed_count} entities using index() in loop") assert len(grid.entities) == 5, f"Expected 5 entities remaining, got {len(grid.entities)}" print("\n✅ Issue #73 test PASSED - Entity.index() method works correctly") sys.exit(0) # Execute the test after a short delay import mcrfpy mcrfpy.setTimer("test", test_entity_index, 100)