Skip to content

Commit e70a239

Browse files
committed
Refactor snake movement logic
1 parent 99ff79e commit e70a239

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

snake.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,24 @@ def __getitem__(self, index):
2323
return list(self.body)[index]
2424

2525
def change_direction(self, new_direction):
26-
if new_direction.value + self.direction.value:
26+
if not self.direction.is_opposite(new_direction):
2727
self.direction = new_direction
2828

2929
def move(self, grow=False):
30-
tail = self.body[0] if grow else self.body.popleft()
31-
x, y = self.body[-1] if len(self.body) else tail
32-
d_x, d_y = DIRECTION_VECTOR[self.direction]
33-
self.body.append(Point((x + d_x) % self.env_width,
34-
(y + d_y) % self.env_width))
30+
new_head = self.next_position()
31+
if not grow:
32+
self.body.popleft()
33+
self.body.append(new_head)
3534

35+
def next_position(self):
36+
x, y = self.head
37+
dx, dy = DIRECTION_VECTOR[self.direction]
38+
return Point((x + dx) % self.env_width,
39+
(y + dy) % self.env_width)
40+
41+
@property
42+
def head(self):
43+
return self[-1]
3644

3745
@property
3846
def tail(self):

utils.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
from collections import namedtuple
33

44
class Direction(Enum):
5-
NORTH = 1
6-
EAST = 2
7-
SOUTH = -1
8-
WEST = -2
5+
NORTH = 0
6+
EAST = 1
7+
SOUTH = 2
8+
WEST = 3
9+
10+
def is_opposite(self, other):
11+
return self.value + other.value % 2 == 0
912

1013
Point = namedtuple('Point', 'x, y')

0 commit comments

Comments
 (0)