Skip to content
This repository was archived by the owner on Mar 31, 2020. It is now read-only.

Commit 8151d1e

Browse files
committed
Added Coord class for working with coordinates
1 parent b450998 commit 8151d1e

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

src/coord.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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

Comments
 (0)