Build a path slightly longer than the shortest path.
(self, dst: Pos, snake: Snake)
| 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] |
no test coverage detected