MCPcopy
hub / github.com/chynl/snake / longer_path

Method longer_path

src/agents/graph.py:87–132  ·  view source on GitHub ↗

Build a path slightly longer than the shortest path.

(self, dst: Pos, snake: Snake)

Source from the content-addressed store, hash-verified

85 return []
86
87 def longer_path(self, dst: Pos, snake: Snake) -> list[Direction]:
88 """Build a path slightly longer than the shortest path."""
89 shortest = self.shortest_path(dst, snake)
90 longest: list[Direction] = []
91 cur = snake.head()
92
93 for direc in shortest:
94 nxt = cur.adj(direc)
95 extended = False
96
97 test_direcs = []
98 if direc in (Direction.UP, Direction.DOWN):
99 test_direcs = [Direction.LEFT, Direction.RIGHT]
100 else:
101 test_direcs = [Direction.UP, Direction.DOWN]
102
103 for test_direc in test_direcs:
104 cur_extended = cur.adj(test_direc)
105 nxt_extended = nxt.adj(test_direc)
106
107 cur_extendable = (
108 self.is_reachable(cur_extended, snake)
109 # eating the food might trap the snake, so we don't extend if there's food
110 and not snake.is_food(cur_extended)
111 )
112
113 nxt_extendable = (
114 self.is_reachable(nxt_extended, snake)
115 # coords[1] is the second last snake body which will become
116 # the new tail after the move, so it's safe to extend
117 or nxt_extended == snake.coords[1]
118 )
119
120 if cur_extendable and nxt_extendable:
121 longest.append(test_direc)
122 longest.append(direc)
123 longest.append(test_direc.opposite())
124 extended = True
125 break
126
127 if not extended:
128 longest.append(direc)
129
130 cur = nxt
131
132 return longest
133
134 def build_hamilton_index(self, path: list[Direction], snake: Snake) -> None:
135 self.hamilton_index = [list(row) for row in snake.grid]

Callers 1

next_direcMethod · 0.95

Calls 6

shortest_pathMethod · 0.95
is_reachableMethod · 0.95
headMethod · 0.80
adjMethod · 0.80
is_foodMethod · 0.80
oppositeMethod · 0.80

Tested by

no test coverage detected