Skip to content

Commit cdb2984

Browse files
author
sanrishi
committed
perf: replace busy-wait with ontimer in Snake-Game main loop
- Replaced while True + time.sleep with ontimer-based event loop - CPU now only runs game logic when scheduled, not polling at 10 FPS while idle - Removes unnecessary CPU consumption in IDLE/PAUSED/GAME_OVER states - Fixes steam-bell-92#1200
1 parent bf108db commit cdb2984

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

games/Snake-Game/Snake-Game.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -232,12 +232,12 @@ def move():
232232

233233
game_text.write("Press SPACEBAR to Start", align="center", font=("Arial", 24, "bold"))
234234

235-
while True:
235+
def game_loop():
236236
screen.update()
237237

238238
if game_state in ["IDLE", "PAUSED", "GAME_OVER"]:
239-
time.sleep(0.1)
240-
continue
239+
screen.ontimer(game_loop, 100)
240+
return
241241

242242
# Border collision
243243
if (
@@ -250,7 +250,8 @@ def move():
250250
gameover_sound.play()
251251
game_text.write("GAME OVER - Press SPACE to Restart", align="center", font=("Arial", 20, "bold"))
252252
game_state = "GAME_OVER"
253-
continue
253+
screen.ontimer(game_loop, 100)
254+
return
254255

255256
# Food collision
256257
if head.distance(food) < GRID_SIZE:
@@ -268,7 +269,6 @@ def move():
268269
game_text.clear()
269270
game_text.write(f"LEVEL {level}", align="center", font=("Arial", 24, "bold"))
270271
screen.update()
271-
time.sleep(0.5)
272272
game_text.clear()
273273

274274
generate_food()
@@ -301,9 +301,12 @@ def move():
301301
break
302302

303303
if game_state == "GAME_OVER":
304-
continue
304+
screen.ontimer(game_loop, 100)
305+
return
305306

306-
time.sleep(speed)
307+
screen.ontimer(game_loop, int(speed * 1000))
308+
309+
screen.ontimer(game_loop, 100)
307310

308311
if __name__ == '__main__':
309312
main()

0 commit comments

Comments
 (0)