|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import operator |
| 4 | +from typing import NamedTuple, Callable, TypeVar |
| 5 | +from functools import partialmethod |
| 6 | + |
| 7 | + |
| 8 | +class Coord(NamedTuple): |
| 9 | + """ |
| 10 | + Helper class for managing coordinate values. |
| 11 | +
|
| 12 | + Coord overloads many of the numeric |
| 13 | +
|
| 14 | + param |
| 15 | + x: float -- X position. |
| 16 | + y: float -- Y position |
| 17 | + """ |
| 18 | + |
| 19 | + x: int |
| 20 | + y: int |
| 21 | + |
| 22 | + Operand = TypeVar('Operand', 'Coord', int) |
| 23 | + |
| 24 | + def __apply(self, op: Callable, other: Coord.Operand) -> Coord: |
| 25 | + if isinstance(other, int): |
| 26 | + other = Coord(other, other) |
| 27 | + |
| 28 | + x = op(self.x, other.x) |
| 29 | + y = op(self.y, other.y) |
| 30 | + return Coord(x, y) |
| 31 | + |
| 32 | + @property |
| 33 | + def midpoint(self) -> Coord: |
| 34 | + return self // Coord(2, 2) |
| 35 | + |
| 36 | + __add__ = partialmethod(__apply, operator.add) |
| 37 | + __sub__ = partialmethod(__apply, operator.sub) |
| 38 | + __mul__ = partialmethod(__apply, operator.mul) |
| 39 | + __mod__ = partialmethod(__apply, operator.mod) |
| 40 | + __pow__ = partialmethod(__apply, operator.pow) |
| 41 | + __truediv__ = partialmethod(__apply, operator.truediv) |
| 42 | + __floordiv__ = partialmethod(__apply, operator.floordiv) |
0 commit comments