Represents the snake in the game.
| 2 | |
| 3 | |
| 4 | class Snake: |
| 5 | """Represents the snake in the game.""" |
| 6 | |
| 7 | def __init__(self, init_length=3): |
| 8 | """Initializes the snake. |
| 9 | |
| 10 | Args: |
| 11 | init_length (int): Length of the snake on initialization. |
| 12 | """ |
| 13 | self.head = Point(GameSettings.WIDTH / 2, GameSettings.HEIGHT / 2) |
| 14 | self.block_size = GameSettings.BLOCK_SIZE |
| 15 | self.blocks = [self.head] + [ |
| 16 | Point(self.head.x - (i * self.block_size), self.head.y) |
| 17 | for i in range(1, init_length) |
| 18 | ] |
| 19 | self.direction = Direction.RIGHT |
| 20 | |
| 21 | def move(self, direction): |
| 22 | """Moves the snake in the given direction. |
| 23 | |
| 24 | Args: |
| 25 | direction (Direction): The direction to move the snake. |
| 26 | |
| 27 | Returns: |
| 28 | Point: The new snake head position. |
| 29 | """ |
| 30 | x, y = self.head |
| 31 | if direction == Direction.RIGHT: |
| 32 | x += self.block_size |
| 33 | elif direction == Direction.LEFT: |
| 34 | x -= self.block_size |
| 35 | elif direction == Direction.DOWN: |
| 36 | y += self.block_size |
| 37 | elif direction == Direction.UP: |
| 38 | y -= self.block_size |
| 39 | self.head = Point(x, y) |
| 40 | self.blocks.insert(0, self.head) |
| 41 | return self.head |
| 42 | |
| 43 | def self_collision(self): |
| 44 | """Checks if the snake collides with itself. |
| 45 | |
| 46 | Returns: |
| 47 | bool: True if the snake collides with its body, False otherwise. |
| 48 | """ |
| 49 | if self.head in self.blocks[1:]: |
| 50 | return True |
| 51 | return False |
no outgoing calls