linting ...
[oam.git] / code / network-generator / network_generation / model / python / cube.py
1 # Copyright 2023 highstreet technologies GmbH
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # inspired by http://www.redblobgames.com/grids/hexagons/
16
17 # !/usr/bin/python
18 from network_generation.model.python.hexagon import Hex
19
20
21 class Cube:
22     @staticmethod
23     def direction_vectors() -> list[Hex]:
24         q, r, s = 1, 0, -1
25         return [
26             Hex(q, r, s),
27             Hex(-s, -q, -r),
28             Hex(r, s, q),
29             Hex(-q, -r, -s),
30             Hex(s, q, r),
31             Hex(-r, -s, -q),
32         ]
33
34     @staticmethod
35     def direction(direction: int) -> Hex:
36         if direction < 0 or direction > 5:
37             raise ValueError(
38                 "Invalid direction. The direction value must be"
39                 + " in the range of [0..5]."
40             )
41         return Cube.direction_vectors()[direction]
42
43     @staticmethod
44     def add(hex: Hex, vec: Hex) -> Hex:
45         return Hex(hex.q + vec.q, hex.r + vec.r, hex.s + vec.s)
46
47     @staticmethod
48     def neighbor(cube: Hex, direction: int) -> Hex:
49         return Cube.add(cube, Cube.direction(direction))
50
51     @staticmethod
52     def scale(hex: Hex, factor: int) -> Hex:
53         return Hex(hex.q * factor, hex.r * factor, hex.s * factor)
54
55     @staticmethod
56     def ring(center: Hex, radius: int) -> list[Hex]:
57         if not (radius > 0):
58             raise ValueError(
59                 "Invalid radius. The radius around the hex center must"
60                 + " be greater than 0 rings."
61             )
62         results: list[Hex] = []
63         hex: Hex = Cube.add(center, Cube.scale(Cube.direction(4), radius))
64         for i in range(6):
65             for j in range(radius):
66                 results.append(hex)
67                 hex = Cube.neighbor(hex, i)
68         return results
69
70     @staticmethod
71     def spiral(center: Hex, radius: int) -> list[Hex]:
72         result: list[Hex] = [center]
73         for k in range(1, radius + 1):
74             result.extend(Cube.ring(center, k))
75         return result