Skip to content

Commit b0615ab

Browse files
committed
fix snake game controls
1 parent ac274a0 commit b0615ab

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

docs/source/examples/snake_game.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ class Direction(enum.Enum):
4444
def GameLoop(grid_size, block_scale, set_game_state):
4545
# we `use_ref` here to capture the latest direction press without any delay
4646
direction = idom.hooks.use_ref(Direction.ArrowRight.value)
47+
# capture the last direction of travel that was rendered
48+
last_direction = direction.current
4749

4850
snake, set_snake = idom.hooks.use_state([(grid_size // 2 - 1, grid_size // 2 - 1)])
4951
food, set_food = use_snake_food(grid_size, snake)
@@ -52,11 +54,11 @@ def GameLoop(grid_size, block_scale, set_game_state):
5254
grid_events = grid["eventHandlers"] = idom.Events()
5355

5456
@grid_events.on("KeyDown", prevent_default=True)
55-
async def on_direction_change(event):
57+
def on_direction_change(event):
5658
if hasattr(Direction, event["key"]):
5759
maybe_new_direction = Direction[event["key"]].value
5860
direction_vector_sum = tuple(
59-
map(sum, zip(direction.current, maybe_new_direction))
61+
map(sum, zip(last_direction, maybe_new_direction))
6062
)
6163
if direction_vector_sum != (0, 0):
6264
direction.current = maybe_new_direction

0 commit comments

Comments
 (0)