MCPcopy Create free account
hub / github.com/Mrinank-Bhowmick/python-beginner-projects / Snake

Class Snake

projects/Snake Game/src/snake.py:4–51  ·  view source on GitHub ↗

Represents the snake in the game.

Source from the content-addressed store, hash-verified

2
3
4class 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

Callers 5

__init__Method · 0.90
restart_gameMethod · 0.90
test_restart_gameMethod · 0.90
setUpMethod · 0.90
setUpMethod · 0.90

Calls

no outgoing calls

Tested by 3

test_restart_gameMethod · 0.72
setUpMethod · 0.72
setUpMethod · 0.72