AI-Snake-Game/tests/test_snake.py

73 lines
2.2 KiB
Python

from src.core import Snake, Direction
def test_snake_initialization():
"""Test snake initialization with default values"""
snake = Snake((100, 100), 20)
assert snake.block_size == 20
assert snake.direction == Direction.RIGHT
assert len(snake.body) == 1
assert snake.body[0] == (100, 100)
assert not snake.growing
def test_snake_movement():
"""Test snake movement in different directions"""
snake = Snake((100, 100), 20)
# Test right movement (default direction)
snake.move(100) # time parameter
assert snake.body[0] == (120, 100)
# Test down movement
snake.change_direction(Direction.DOWN)
snake.move(200)
assert snake.body[0] == (120, 120)
# Test left movement
snake.change_direction(Direction.LEFT)
snake.move(300)
assert snake.body[0] == (100, 120)
# Test up movement
snake.change_direction(Direction.UP)
snake.move(400)
assert snake.body[0] == (100, 100)
def test_snake_growth():
"""Test snake growth when eating food"""
snake = Snake((100, 100), 20)
original_length = len(snake.body)
snake.grow()
snake.move(100)
assert len(snake.body) == original_length + 1
def test_snake_collision():
"""Test snake collision detection"""
snake = Snake((100, 100), 20)
# Test wall collision
assert snake.check_collision(200, 200) == False # No collision
snake.body[0] = (-20, 100) # Move outside left wall
assert snake.check_collision(200, 200) == True
# Test self collision
snake = Snake((100, 100), 20)
snake.body = [(100, 100), (120, 100), (120, 120), (100, 120), (100, 100)]
assert snake.check_collision(200, 200) == True
def test_invalid_direction_change():
"""Test that snake cannot reverse direction"""
snake = Snake((100, 100), 20)
# Try to change to opposite direction (LEFT while going RIGHT)
snake.change_direction(Direction.LEFT)
assert snake.direction == Direction.RIGHT
# Valid direction change
snake.change_direction(Direction.DOWN)
assert snake.direction == Direction.DOWN
# Try to change to opposite direction (UP while going DOWN)
snake.change_direction(Direction.UP)
assert snake.direction == Direction.DOWN