File tree 2 files changed +21
-10
lines changed
2 files changed +21
-10
lines changed Original file line number Diff line number Diff line change @@ -23,16 +23,24 @@ def __getitem__(self, index):
23
23
return list (self .body )[index ]
24
24
25
25
def change_direction (self , new_direction ):
26
- if new_direction . value + self .direction .value :
26
+ if not self .direction .is_opposite ( new_direction ) :
27
27
self .direction = new_direction
28
28
29
29
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 )
35
34
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 ]
36
44
37
45
@property
38
46
def tail (self ):
Original file line number Diff line number Diff line change 2
2
from collections import namedtuple
3
3
4
4
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
9
12
10
13
Point = namedtuple ('Point' , 'x, y' )
You can’t perform that action at this time.
0 commit comments