Refine the geometry classes; add __add__ method for Points and Vectors

This commit is contained in:
Eryn Wells 2022-05-01 09:26:20 -07:00
parent 7f225e9e01
commit a422a74a17

View file

@ -1,7 +1,7 @@
#!/usr/bin/env python3
# Eryn Wells <eryn@erynwells.me>
from typing import Tuple
from typing import Tuple, overload
class Point:
__slots__ = ('x', 'y')
@ -10,6 +10,16 @@ class Point:
self.x = x
self.y = y
@overload
def __add__(self, other: Vector) -> Point:
...
@overload
def __add__(self, other) -> Point:
if not isinstance(other, Vector):
raise TypeError('Only Vector can be added to a Point')
return Point(self.x + other.dx, self.y + other.dy)
def __str__(self):
return f'(x:{self.x}, y:{self.y})'
@ -58,26 +68,32 @@ class Rect:
@property
def min_x(self) -> int:
'''Minimum x-value that is still within the bounds of this rectangle. This is the origin's x-value.'''
return self.origin.x
@property
def min_y(self) -> int:
'''Minimum y-value that is still within the bounds of this rectangle. This is the origin's y-value.'''
return self.origin.y
@property
def mid_x(self) -> int:
'''The x-value of the center point of this rectangle.'''
return int(self.origin.x + self.size.width / 2)
@property
def mid_y(self) -> int:
'''The y-value of the center point of this rectangle.'''
return int(self.origin.y + self.size.height / 2)
@property
def max_x(self) -> int:
'''Maximum x-value that is still within the bounds of this rectangle.'''
return self.origin.x + self.size.width - 1
@property
def max_y(self) -> int:
'''Maximum y-value that is still within the bounds of this rectangle.'''
return self.origin.y + self.size.height - 1
@property
@ -85,7 +101,7 @@ class Rect:
return Point(self.mid_x, self.mid_y)
def __str__(self):
return f'({self.origin}, {self.size})'
return f'[{self.origin}, {self.size}]'
def __repr__(self):
return f'Rect({self.origin.x}, {self.origin.y}, {self.size.width}, {self.size.height})'
return f'{self.__class__.__name__}({self.origin.x}, {self.origin.y}, {self.size.width}, {self.size.height})'