Skip to content

Commit

Permalink
Use math.copysign to get the sign of dx, dy. (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
wlame committed Apr 6, 2024
1 parent a8a6bfe commit bcb769c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
__pycache__/
.pytest_cache/

.coverage
.coverage

dist/
21 changes: 12 additions & 9 deletions hexometry.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""Hexometry module"""

import collections
import enum
import math
import random
import functools
from collections import namedtuple
from enum import Enum

from typing import TypeAlias, Iterator


Expand All @@ -12,7 +15,7 @@
_FLOAT_PRECISION = 4


class Direction(Enum):
class Direction(enum.Enum):
"""Hexagonal directions"""
NE = '↗'
E = '→'
Expand Down Expand Up @@ -53,7 +56,7 @@ def __hash__(self) -> int:
DecartCoord: TypeAlias = tuple[float, float]


class Coord(namedtuple('Coord', ['x', 'y'])):
class Coord(collections.namedtuple('Coord', ['x', 'y'])):
"""Hexagonal coordinate.
While `x` and `y` are enough to identify a hexagon,
`z` coordinate can be calculated as -x-y and is useful in some calculations.
Expand Down Expand Up @@ -94,7 +97,7 @@ def get_route(start: Coord, end: Coord, shuffle: bool = False) -> Route:
if shuffle is True, directions in a route will be shuffled
"""
# grad_x: {grad_y: direction} — coordinates gradients for each direction
XY = {
gradients = {
0: {1: Direction.NE, -1: Direction.SW},
1: {0: Direction.E, -1: Direction.SE},
-1: {0: Direction.W, 1: Direction.NW},
Expand All @@ -105,12 +108,12 @@ def get_route(start: Coord, end: Coord, shuffle: bool = False) -> Route:

route = []
while dx != 0 or dy != 0:
grad_x = int(dx / abs(dx)) if dx != 0 else 0
grad_y = int(dy / abs(dy)) if dy != 0 else 0
grad_x = math.copysign(1, dx) if dx != 0 else 0
grad_y = math.copysign(1, dy) if dy != 0 else 0

grad_y = grad_y if grad_y in XY[grad_x] else next(iter(XY[grad_x]))
grad_y = grad_y if grad_y in gradients[grad_x] else next(iter(gradients[grad_x]))

route.append(XY[grad_x][grad_y])
route.append(gradients[grad_x][grad_y])

dx -= grad_x
dy -= grad_y
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi"

[project]
name = "hexometry"
authors = [{name = "wlame", email = "[email protected]"}]
authors = [{name = "wlame", email = "[email protected]"}]
readme = "README.md"
license = {file = "LICENSE"}
classifiers = ["License :: OSI Approved :: MIT License"]
Expand Down

0 comments on commit bcb769c

Please sign in to comment.