Untitled
unknown
plain_text
25 days ago
3.0 kB
2
Indexable
Never
def hex_spiral_index(q, r): """ Computes the spiral index of a hex grid cell given its axial coordinates (q, r). The spiral starts at (0, 0) with index 1 and expands outward in rings. Parameters: q (int): Axial coordinate q. r (int): Axial coordinate r. Returns: int: Spiral index of the cell. """ # Calculate the ring number (distance from center) n = max(abs(q), abs(r), abs(-q - r)) if n == 0: return 1 # The center cell # Total number of cells before the current ring total_cells_before_ring = 1 + 3 * n * (n - 1) # Define starting positions for each side of the ring positions = [ (0, -n), # Side 0 start (East) (n, -n), # Side 1 start (Southeast) (n, 0), # Side 2 start (Southwest) (0, n), # Side 3 start (West) (-n, n), # Side 4 start (Northwest) (-n, 0) # Side 5 start (Northeast) ] # Directions for each side directions = [ (1, 0), # East (0, 1), # Southeast (-1, 1), # Southwest (-1, 0), # West (0, -1), # Northwest (1, -1) # Northeast ] # Check if the cell is on the current ring for side in range(6): x0, y0 = positions[side] dx, dy = directions[side] for t in range(n): x = x0 + t * dx y = y0 + t * dy if x == q and y == r: # Calculate steps along the ring steps = side * n + t index = total_cells_before_ring + steps + 1 return index # If not found, the cell is in an inner ring # Recursively compute the index for the inner ring return hex_spiral_index_inner(q, r, n - 1) def hex_spiral_index_inner(q, r, n): if n == 0: return 1 # The center cell # Total number of cells before the current ring total_cells_before_ring = 1 + 3 * n * (n - 1) # Define starting positions and directions as before positions = [ (0, -n), (n, -n), (n, 0), (0, n), (-n, n), (-n, 0) ] directions = [ (1, 0), (0, 1), (-1, 1), (-1, 0), (0, -1), (1, -1) ] # Check if the cell is on the current ring for side in range(6): x0, y0 = positions[side] dx, dy = directions[side] for t in range(n): x = x0 + t * dx y = y0 + t * dy if x == q and y == r: steps = side * n + t index = total_cells_before_ring + steps + 1 return index # Recursively check the next inner ring return hex_spiral_index_inner(q, r, n - 1) # Example usage: if __name__ == "__main__": q, r = map(int, input("Enter axial coordinates q and r: ").split()) index = hex_spiral_index(q, r) print(f"The spiral index of cell ({q}, {r}) is {index}")
Leave a Comment