Skip to content

Commit 83b480a

Browse files
committed
fix(ism330dl): Fix recursive game loop and add cleanup in maze_game.
Address review comments on #390: 1. Replace recursive run_game() self-call with an outer `while True` loop. On MicroPython's limited stack (8-16 KB), each completed game added a stack frame that was never freed — a few wins would crash with a RecursionError or silent stack overflow. 2. Add try/except/finally around the game loop: Ctrl+C now cleanly clears the display and powers off the IMU (same pattern as spirit_level.py) to avoid battery drain. 3. Add maze_game.py to the README examples table.
1 parent 700b587 commit 83b480a

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

lib/ism330dl/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,5 +286,6 @@ The repository provides several example scripts:
286286
| `static_orientation.py` | Detect device orientation using the accelerometer |
287287
| `motion_orientation.py` | Detect rotation using the gyroscope |
288288
| `spirit_level.py` | Interactive digital bubble level using SSD1327 OLED|
289+
| `maze_game.py` | Tilt-controlled maze game with score on SSD1327 OLED|
289290

290291
---

lib/ism330dl/examples/maze_game.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,10 @@ def show_win_screen(steps, optimal):
250250

251251

252252
def run_game():
253-
"""Generate a new maze and run one full game."""
253+
"""Generate a new maze and run one full game round.
254+
255+
Returns when the player reaches the goal.
256+
"""
254257
maze = generate_maze(MAZE_W, MAZE_H)
255258
optimal = dijkstra(maze, START_ROW, START_COL, GOAL_ROW, GOAL_COL)
256259

@@ -273,10 +276,8 @@ def run_game():
273276
player_col = nc
274277
steps += 1
275278

276-
# Check win condition
277279
if player_row == GOAL_ROW and player_col == GOAL_COL:
278280
show_win_screen(steps, optimal)
279-
run_game()
280281
return
281282

282283
sleep_ms(MOVE_DELAY_MS)
@@ -287,4 +288,13 @@ def run_game():
287288
# =============================================================================
288289

289290
print("Maze game starting...")
290-
run_game()
291+
292+
try:
293+
while True:
294+
run_game()
295+
except KeyboardInterrupt:
296+
print("\nMaze game stopped.")
297+
finally:
298+
screen.clear()
299+
screen.show()
300+
imu.power_off()

0 commit comments

Comments
 (0)