Util function to get the direction from start point to destination point. Args: point1(Point), the start point. point2(Point), the end point. Return: str: the direction.
(point1:Point, point2:Point)
| 100 | |
| 101 | # Util function starts. ======================== |
| 102 | def get_direction(point1:Point, point2:Point) -> Direction: |
| 103 | """ |
| 104 | Util function to get the direction from start point to destination point. |
| 105 | |
| 106 | Args: |
| 107 | point1(Point), the start point. |
| 108 | point2(Point), the end point. |
| 109 | |
| 110 | Return: |
| 111 | str: the direction. |
| 112 | """ |
| 113 | # Get the coordinate of two points. |
| 114 | try: |
| 115 | x1, y1 = point1["x"], point1["y"] |
| 116 | x2, y2 = point2["x"], point2["y"] |
| 117 | |
| 118 | assert x1 is not None |
| 119 | assert x2 is not None |
| 120 | assert y1 is not None |
| 121 | assert y2 is not None |
| 122 | |
| 123 | vector = (x2 - x1, y2 - y1) |
| 124 | vx, vy = vector |
| 125 | except Exception as e: |
| 126 | return "no direction" |
| 127 | |
| 128 | # Define the direction vector. |
| 129 | directions = { |
| 130 | "up": (0, -1), |
| 131 | "down": (0, 1), |
| 132 | "left": (-1, 0), |
| 133 | "right": (1, 0) |
| 134 | } |
| 135 | |
| 136 | vector_length = math.sqrt(vx ** 2 + vy ** 2) |
| 137 | if vector_length == 0: # same point. |
| 138 | return "no direction" |
| 139 | unit_vector = (vx / vector_length, vy / vector_length) |
| 140 | |
| 141 | # Calculate the cosine of each direction. |
| 142 | max_cosine = -float('inf') |
| 143 | closest_direction = None |
| 144 | for direction, dir_vector in directions.items(): |
| 145 | dx, dy = dir_vector |
| 146 | dir_length = math.sqrt(dx ** 2 + dy ** 2) |
| 147 | cos_theta = (unit_vector[0] * dx + unit_vector[1] * dy) / dir_length |
| 148 | if cos_theta > max_cosine: |
| 149 | max_cosine = cos_theta |
| 150 | closest_direction = direction |
| 151 | |
| 152 | return closest_direction |
| 153 | |
| 154 | |
| 155 | def transform_actions(action:dict) -> str: |