diff --git a/examples/snake_example.py b/examples/snake_example.py index af7bedd..6630dd7 100644 --- a/examples/snake_example.py +++ b/examples/snake_example.py @@ -21,6 +21,23 @@ class Direction(Enum): LEFT = 4 +def determine_snake_direction(event_key: int, snake_direction: Direction) -> Direction: + if event_key == pygame.K_UP and \ + snake_direction != Direction.DOWN: + return Direction.UP + elif event_key == pygame.K_RIGHT and \ + snake_direction != Direction.LEFT: + return Direction.RIGHT + elif event_key == pygame.K_DOWN and \ + snake_direction != Direction.UP: + return Direction.DOWN + elif event_key == pygame.K_LEFT and \ + snake_direction != Direction.RIGHT: + return Direction.LEFT + + return snake_direction + + def determine_snake_position(snake_direction: Direction, snake_head_top: int, snake_head_left: int) -> tuple: if snake_direction == Direction.UP: snake_head_top -= 1 @@ -38,7 +55,7 @@ def determine_snake_position(snake_direction: Direction, snake_head_top: int, sn snake_head_left -= 1 if snake_head_left == -1: snake_head_left = 9 - + return snake_head_top, snake_head_left @@ -85,18 +102,8 @@ def start_snake_example() -> None: if event.key == pygame.K_ESCAPE: running = False break - if event.key == pygame.K_UP and \ - snake_direction != Direction.DOWN: - snake_direction = Direction.UP - elif event.key == pygame.K_RIGHT and \ - snake_direction != Direction.LEFT: - snake_direction = Direction.RIGHT - elif event.key == pygame.K_DOWN and \ - snake_direction != Direction.UP: - snake_direction = Direction.DOWN - elif event.key == pygame.K_LEFT and \ - snake_direction != Direction.RIGHT: - snake_direction = Direction.LEFT + + snake_direction = determine_snake_direction(event.key, snake_direction) # Draw border border = shape_factory.Rect(0, 0, grid.width_gap(0, 10),