-
Notifications
You must be signed in to change notification settings - Fork 1
/
shapes.py
1006 lines (756 loc) · 30.3 KB
/
shapes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import division
import math
import random
import operator
# Utility Functions
def cast_anything_to_vector(input):
if isinstance(input, Vector):
return input
# If the input object is a container with two elements, use those elements
# to construct a vector.
try: return Vector(*input)
except: pass
# If the input object has x and y attributes, use those attributes to
# construct a vector.
try: return Vector(input.x, input.y)
except: pass
# If the function has returned by now, the input object could not be cast
# to a vector. Throw an exception.
raise VectorCastError(input)
def cast_anything_to_rectangle(input):
# If the input object implements the shape interface, use that information
# to directly return a rectangle object.
try: return cast_shape_to_rectangle(input)
except: pass
# If the input object can be cast to a vector, try to represent that vector
# as a rectangle. Such a rectangle is located where the vector points and
# has no area (i.e. width = height = 0).
try: return Rectangle.from_vector(input)
except: pass
# If the function has returned by now, the input object could not be cast
# to a rectangle. Throw an exception.
raise RectangleCastError(input)
def cast_shape_to_rectangle(input):
if isinstance(input, Rectangle):
return input
# If the input object implements the shape interface (i.e. has bottom, left,
# width, and height attributes), use that information to construct a bona
# fide rectangle object.
try: return Rectangle.from_shape(input)
except: pass
raise RectangleCastError(input)
def accept_anything_as_vector(function):
def decorator(self, *input):
if len(input) == 1: input = input[0]
vector = cast_anything_to_vector(input)
return function(self, vector)
return decorator
def accept_anything_as_rectangle(function):
def decorator(self, input):
rect = cast_anything_to_rectangle(input)
return function(self, rect)
return decorator
def accept_shape_as_rectangle(function):
def decorator(self, input):
rect = cast_shape_to_rectangle(input)
return function(self, rect)
return decorator
def _overload_left_side(f, scalar_ok=False):
def operator(self, other):
try: x, y = cast_anything_to_vector(other)
except: pass
else: return Vector(f(self.x, x), f(self.y, y))
# Zero is treated as a special case, because the built-in sum()
# function expects to be able to add zero to things.
if (other is 0) or (scalar_ok):
return Vector(f(self.x, other), f(self.y, other))
else:
raise VectorCastError(other)
return operator
def _overload_right_side(f, scalar_ok=False):
def operator(self, other):
try: x, y = cast_anything_to_vector(other)
except: pass
else: return Vector(f(x, self.x), f(y, self.y))
if (other is 0) or (scalar_ok):
return Vector(f(other, self.x), f(other, self.y))
else:
raise VectorCastError(other)
return operator
def _overload_in_place(f, scalar_ok=False):
def operator(self, other):
try: x, y = cast_anything_to_vector(other)
except: pass
else: self.x, self.y = f(self.x, x), f(self.y, y); return self
if (other is 0) or (scalar_ok):
self.x, self.y = f(self.x, other), f(self.y, other)
return self
else:
raise VectorCastError(other)
return operator
# Geometry Functions
golden_ratio = 1/2 + math.sqrt(5) / 2
class Shape (object):
""" Provide an interface for custom shape classes to interact with the
rectangle class. For example, rectangles can be instantiated from shapes
and can test for collisions against shapes. The interface is very simple,
requiring only four methods to be redefined. """
def get_bottom(self):
raise NotImplementedError
def get_left(self):
raise NotImplementedError
def get_width(self):
raise NotImplementedError
def get_height(self):
raise NotImplementedError
# Properties (fold)
bottom = property(get_bottom)
left = property(get_left)
width = property(get_width)
height = property(get_height)
class Vector (object):
""" Represents a two-dimensional vector. In particular, this class
features a number of factory methods to create vectors from various inputs
and a number of overloaded operators to facilitate vector arithmetic. """
@staticmethod
def null():
""" Return a null vector. """
return Vector(0, 0)
@staticmethod
def random(magnitude=1):
""" Create a unit vector pointing in a random direction. """
theta = random.uniform(0, 2 * math.pi)
return magnitude * Vector(math.cos(theta), math.sin(theta))
@staticmethod
def from_radians(angle):
""" Create a unit vector that makes the given angle with the x-axis. """
return Vector(math.cos(angle), math.sin(angle))
@staticmethod
def from_degrees(angle):
""" Create a unit vector that makes the given angle with the x-axis. """
return Vector.from_radians(angle * math.pi / 180)
@staticmethod
def from_tuple(coordinates):
""" Create a vector from a two element tuple. """
return Vector(*coordinates)
@staticmethod
def from_scalar(scalar):
""" Create a vector from a single scalar value. """
return Vector(scalar, scalar)
@staticmethod
def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y)
def copy(self):
""" Return a copy of this vector. """
from copy import deepcopy
return deepcopy(self)
@accept_anything_as_vector
def assign(self, other):
""" Copy the given vector into this one. """
self.x, self.y = other.tuple
def normalize(self):
""" Set the magnitude of this vector to unity, in place. """
try:
self /= self.magnitude
except ZeroDivisionError:
raise NullVectorError
def scale(self, magnitude):
""" Set the magnitude of this vector in place. """
self.normalize()
self *= magnitude
def interpolate(self, target, extent):
""" Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. """
target = cast_anything_to_vector(target)
self += extent * (target - self)
@accept_anything_as_vector
def project(self, axis):
""" Project this vector onto the given axis. """
projection = self.get_projection(axis)
self.assign(projection)
@accept_anything_as_vector
def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y
@accept_anything_as_vector
def perp_product(self, other):
""" Return the perp product of the given vectors. The perp product is
just a cross product where the third dimension is taken to be zero and
the result is returned as a scalar. """
return self.x * other.y - self.y * other.x
def rotate(self, angle):
""" Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """
x, y = self.tuple
self.x = x * math.cos(angle) - y * math.sin(angle)
self.y = x * math.sin(angle) + y * math.cos(angle)
def round(self, digits):
""" Round the elements of the given vector to the given number of digits. """
# Meant as a way to clean up Vector.rotate()
# For example:
# V = Vector(1,0)
# V.rotate(2*pi)
#
# V is now <1.0, -2.4492935982947064e-16>, when it should be
# <1,0>. V.round(15) will correct the error in this example.
x, y = self.tuple
self.x = round(x, digits)
self.y = round(y, digits)
def __init__(self, x, y):
""" Construct a vector using the given coordinates. """
self.x = x
self.y = y
def __repr__(self):
""" Return a string representation of this vector. """
return "Vector(%f, %f)" % self.tuple
def __str__(self):
""" Return a string representation of this vector. """
return "<%.2f, %.2f>" % self.tuple
def __iter__(self):
""" Iterate over this vectors coordinates. """
yield self.x; yield self.y
def __bool__(self):
""" Return true is the vector is not degenerate. """
return self != (0, 0)
__nonzero__ = __bool__
def __getitem__(self, i):
""" Return the specified coordinate. """
return self.tuple[i]
def __eq__(self, other):
"""Return true if the given object has the same coordinates as this
vector."""
try:
other = cast_anything_to_vector(other)
return self.x == other.x and self.y == other.y
except VectorCastError:
return False
def __ne__(self, other):
"""Return true if the given object has different coordinates than this
vector."""
return not self.__eq__(other)
def __neg__(self):
""" Return a copy of this vector with the signs flipped. """
return Vector(-self.x, -self.y)
def __abs__(self):
""" Return the absolute value of this vector. """
return Vector(abs(self.x), abs(self.y))
# Binary Operators (fold)
__add__ = _overload_left_side(operator.add)
__radd__ = _overload_right_side(operator.add)
__iadd__ = _overload_in_place(operator.add)
__sub__ = _overload_left_side(operator.sub)
__rsub__ = _overload_right_side(operator.sub)
__isub__ = _overload_in_place(operator.sub)
__mul__ = _overload_left_side(operator.mul, scalar_ok=True)
__rmul__ = _overload_right_side(operator.mul, scalar_ok=True)
__imul__ = _overload_in_place(operator.mul, scalar_ok=True)
__floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True)
__rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True)
__ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True)
__truediv__ = _overload_left_side(operator.truediv, scalar_ok=True)
__rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True)
__itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True)
__div__ = __truediv__
__rdiv__ = __rtruediv__
__idiv__ = __itruediv__
__mod__ = _overload_left_side(operator.mod, scalar_ok=True)
__rmod__ = _overload_right_side(operator.mod, scalar_ok=True)
__imod__ = _overload_in_place(operator.mod, scalar_ok=True)
__pow__ = _overload_left_side(operator.pow, scalar_ok=True)
__rpow__ = _overload_right_side(operator.pow, scalar_ok=True)
__ipow__ = _overload_in_place(operator.pow, scalar_ok=True)
def get_x(self):
""" Get the x coordinate of this vector. """
return self.x
def get_y(self):
""" Get the y coordinate of this vector. """
return self.y
def get_xy(self):
""" Return the vector as a tuple. """
return self.x, self.y
def get_tuple(self):
""" Return the vector as a tuple. """
return self.x, self.y
def get_magnitude(self):
""" Calculate the length of this vector. """
return math.sqrt(self.magnitude_squared)
def get_magnitude_squared(self):
""" Calculate the square of the length of this vector. This is
slightly more efficient that finding the real length. """
return self.x**2 + self.y**2
@accept_anything_as_vector
def get_distance(self, other):
""" Return the Euclidean distance between the two input vectors. """
return (other - self).magnitude
@accept_anything_as_vector
def get_manhattan(self, other):
""" Return the Manhattan distance between the two input vectors. """
return sum(abs(other - self))
def get_unit(self):
""" Return a unit vector parallel to this one. """
result = self.copy()
result.normalize()
return result
def get_orthogonal(self):
""" Return a vector that is orthogonal to this one. The resulting
vector is not normalized. """
return Vector(-self.y, self.x)
def get_orthonormal(self):
""" Return a vector that is orthogonal to this one and that has been
normalized. """
return self.orthogonal.unit
def get_scaled(self, magnitude):
""" Return a unit vector parallel to this one. """
result = self.copy()
result.scale(magnitude)
return result
def get_interpolated(self, target, extent):
""" Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. """
result = self.copy()
result.interpolate(target, extent)
return result
@accept_anything_as_vector
def get_projection(self, axis):
""" Return the projection of this vector onto the given axis. The
axis does not need to be normalized. """
scale = axis.dot(self) / axis.dot(axis)
return axis * scale
@accept_anything_as_vector
def get_components(self, other):
""" Break this vector into one vector that is perpendicular to the
given vector and another that is parallel to it. """
tangent = self.get_projection(other)
normal = self - tangent
return normal, tangent
def get_radians(self):
""" Return the angle between this vector and the positive x-axis
measured in radians. Result will be between -pi and pi. """
if not self: raise NullVectorError()
return math.atan2(self.y, self.x)
def get_positive_radians(self):
""" Return the positive angle between this vector and the positive x-axis
measured in radians. """
return (2 * math.pi + self.get_radians()) % (2 * math.pi)
def get_degrees(self):
""" Return the angle between this vector and the positive x-axis
measured in degrees. """
return self.radians * 180 / math.pi
@accept_anything_as_vector
def get_radians_to(self, other):
""" Return the angle between the two given vectors in radians. If
either of the inputs are null vectors, an exception is thrown. """
return other.radians - self.radians
@accept_anything_as_vector
def get_degrees_to(self, other):
""" Return the angle between the two given vectors in degrees. If
either of the inputs are null vectors, an exception is thrown. """
return other.degrees - self.degrees
def get_rotated(self, angle):
""" Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """
result = self.copy()
result.rotate(angle)
return result
def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result
def set_x(self, x):
""" Set the x coordinate of this vector. """
self.x = x
def set_y(self, y):
""" Set the y coordinate of this vector. """
self.y = y
def set_xy(self, xy):
""" Set the x and y coordinates of this vector from a tuple. """
self.x, self.y = xy
def set_radians(self, angle):
""" Set the angle that this vector makes with the x-axis. """
self.x, self.y = math.cos(angle), math.sin(angle)
def set_degrees(self, angle):
""" Set the angle that this vector makes with the x-axis. """
self.set_radians(angle * math.pi / 180)
def set_tuple(self, coordinates):
""" Set the x and y coordinates of this vector. """
self.x, self.y = coordinates
# Aliases (fold)
dot = dot_product
perp = perp_product
# Properties (fold)
xy = property(get_xy, set_xy)
tuple = property(get_tuple, set_tuple)
magnitude = property(get_magnitude, scale)
magnitude_squared = property(get_magnitude_squared)
unit = property(get_unit)
orthogonal = property(get_orthogonal)
orthonormal = property(get_orthonormal)
radians = property(get_radians, set_radians)
degrees = property(get_degrees, set_degrees)
class Rectangle (Shape):
def __init__(self, left, bottom, width, height):
self._left = left
self._bottom = bottom
self._width = width
self._height = height
def __repr__(self):
return "Rectangle(%f, %f, %f, %f)" % self.tuple
def __str__(self):
return '<Rect bottom={0} left={1} width={2} height={3}>'.format(
self.bottom, self.left, self.width, self.height)
def __eq__(self, other):
try:
return (self.bottom == other.bottom and
self.left == other.left and
self.width == other.width and
self.height == other.height)
except AttributeError:
return False
@accept_anything_as_vector
def __add__(self, vector):
result = self.copy()
result.displace(vector)
return result
@accept_anything_as_vector
def __iadd__(self, vector):
self.displace(vector)
return self
@accept_anything_as_vector
def __sub__(self, vector):
result = self.copy()
result.displace(-vector)
return result
@accept_anything_as_vector
def __isub__(self, vector):
self.displace(-vector)
return self
def __contains__(self, other):
return self.contains(other)
@staticmethod
def null():
""" Return a rectangle with everything set to zero. It is located at
the origin and has no area. """
return Rectangle(0, 0, 0, 0)
@staticmethod
def from_size(width, height):
return Rectangle(0, 0, width, height)
@staticmethod
def from_width(width, ratio=1/golden_ratio):
return Rectangle.from_size(width, ratio * width)
@staticmethod
def from_height(height, ratio=golden_ratio):
return Rectangle.from_size(ratio * height, height)
@staticmethod
def from_square(size):
return Rectangle.from_size(size, size)
@staticmethod
def from_dimensions(left, bottom, width, height):
return Rectangle(left, bottom, width, height)
@staticmethod
def from_sides(left, top, right, bottom):
width = right - left; height = top - bottom
return Rectangle.from_dimensions(left, bottom, width, height)
@staticmethod
def from_corners(first, second):
first = cast_anything_to_vector(first)
second = cast_anything_to_vector(second)
left = min(first.x, second.x); top = max(first.y, second.y)
right = max(first.x, second.x); bottom = min(first.y, second.y)
return Rectangle.from_sides(left, top, right, bottom)
@staticmethod
def from_bottom_left(position, width, height):
position = cast_anything_to_vector(position)
return Rectangle(position.x, position.y, width, height)
@staticmethod
def from_center(position, width, height):
position = cast_anything_to_vector(position) - (width/2, height/2)
return Rectangle(position.x, position.y, width, height)
@staticmethod
def from_vector(position):
position = cast_anything_to_vector(position)
return Rectangle(position.x, position.y, 0, 0)
@staticmethod
def from_points(*points):
left = min(cast_anything_to_vector(p).x for p in points)
top = max(cast_anything_to_vector(p).y for p in points)
right = max(cast_anything_to_vector(p).x for p in points)
bottom = min(cast_anything_to_vector(p).y for p in points)
return Rectangle.from_sides(left, top, right, bottom)
@staticmethod
def from_shape(shape):
bottom, left = shape.bottom, shape.left
width, height = shape.width, shape.height
return Rectangle(left, bottom, width, height)
@staticmethod
def from_surface(surface):
width, height = surface.get_size()
return Rectangle.from_size(width, height)
@staticmethod
def from_pyglet_window(window):
return Rectangle.from_size(window.width, window.height)
@staticmethod
def from_pyglet_image(image):
return Rectangle.from_size(image.width, image.height)
@staticmethod
def from_union(*inputs):
rectangles = [cast_shape_to_rectangle(x) for x in inputs]
left = min(x.left for x in rectangles)
top = max(x.top for x in rectangles)
right = max(x.right for x in rectangles)
bottom = min(x.bottom for x in rectangles)
return Rectangle.from_sides(left, top, right, bottom)
@staticmethod
def from_intersection(*inputs):
rectangles = [cast_shape_to_rectangle(x) for x in inputs]
left = max(x.left for x in rectangles)
top = min(x.top for x in rectangles)
right = min(x.right for x in rectangles)
bottom = max(x.bottom for x in rectangles)
return Rectangle.from_sides(left, top, right, bottom)
def grow(self, padding):
""" Grow this rectangle by the given padding on all sides. """
self._bottom -= padding
self._left -= padding
self._width += 2 * padding
self._height += 2 * padding
return self
def shrink(self, padding):
""" Shrink this rectangle by the given padding on all sides. """
self.grow(-padding)
return self
@accept_anything_as_vector
def displace(self, vector):
""" Displace this rectangle by the given vector. """
self._bottom += vector.y
self._left += vector.x
return self
def set(self, shape):
""" Fill this rectangle with the dimensions of the given shape. """
self.bottom, self.left = shape.bottom, shape.left
self.width, self.height = shape.width, shape.height
return self
def copy(self):
""" Return a copy of this rectangle. """
from copy import deepcopy
return deepcopy(self)
@accept_shape_as_rectangle
def inside(self, other):
""" Return true if this rectangle is inside the given shape. """
return ( self.left >= other.left and
self.right <= other.right and
self.top <= other.top and
self.bottom >= other.bottom)
@accept_anything_as_rectangle
def outside(self, other):
""" Return true if this rectangle is outside the given shape. """
return not self.touching(other)
@accept_anything_as_rectangle
def touching(self, other):
""" Return true if this rectangle is touching the given shape. """
if self.top < other.bottom: return False
if self.bottom > other.top: return False
if self.left > other.right: return False
if self.right < other.left: return False
return True
@accept_anything_as_rectangle
def contains(self, other):
""" Return true if the given shape is inside this rectangle. """
return (self.left <= other.left and
self.right >= other.right and
self.top >= other.top and
self.bottom <= other.bottom)
@accept_anything_as_rectangle
def align_left(self, target):
self.left = target.left
@accept_anything_as_rectangle
def align_center_x(self, target):
self.center_x = target.center_x
@accept_anything_as_rectangle
def align_right(self, target):
self.right = target.right
@accept_anything_as_rectangle
def align_top(self, target):
self.top = target.top
@accept_anything_as_rectangle
def align_center_y(self, target):
self.center_y = target.center_y
@accept_anything_as_rectangle
def align_bottom(self, target):
self.bottom = target.bottom
def get_left(self):
return self._left
def get_center_x(self):
return self._left + self._width / 2
def get_right(self):
return self._left + self._width
def get_top(self):
return self._bottom + self._height
def get_center_y(self):
return self._bottom + self._height / 2
def get_bottom(self):
return self._bottom
def get_width(self):
return self._width
def get_height(self):
return self._height
def get_half_width(self):
return self._width / 2
def get_half_height(self):
return self._height / 2
def get_size(self):
return self._width, self._height
def get_size_as_int(self):
from math import ceil
return int(ceil(self._width)), int(ceil(self._height))
def get_top_left(self):
return Vector(self.left, self.top)
def get_top_center(self):
return Vector(self.center_x, self.top)
def get_top_right(self):
return Vector(self.right, self.top)
def get_center_left(self):
return Vector(self.left, self.center_y)
def get_center(self):
return Vector(self.center_x, self.center_y)
def get_center_right(self):
return Vector(self.right, self.center_y)
def get_bottom_left(self):
return Vector(self.left, self.bottom)
def get_bottom_center(self):
return Vector(self.center_x, self.bottom)
def get_bottom_right(self):
return Vector(self.right, self.bottom)
def get_vertices(self):
return self.top_left, self.top_right, self.bottom_right, self.bottom_left
def get_dimensions(self):
return (self._left, self._bottom), (self._width, self._height)
def get_tuple(self):
return self._left, self._bottom, self._width, self._height
def get_union(self, *rectangles):
return Rectangle.from_union(self, *rectangles)
def get_intersection(self, *rectangles):
return Rectangle.from_intersection(self, *rectangles)
def get_grown(self, padding):
result = self.copy()
result.grow(padding)
return result
def get_shrunk(self, padding):
result = self.copy()
result.shrink(padding)
return result
def set_left(self, x):
self._left = x
def set_center_x(self, x):
self._left = x - self._width / 2
def set_right(self, x):
self._left = x - self._width
def set_top(self, y):
self._bottom = y - self._height
def set_center_y(self, y):
self._bottom = y - self._height / 2
def set_bottom(self, y):
self._bottom = y
def set_width(self, width):
self._width = width
def set_height(self, height):
self._height = height
def set_size(self, width, height):
self._width = width
self._height = height
@accept_anything_as_vector
def set_top_left(self, point):
self.top = point[1]
self.left = point[0]
@accept_anything_as_vector
def set_top_center(self, point):
self.top = point[1]
self.center_x = point[0]
@accept_anything_as_vector
def set_top_right(self, point):
self.top = point[1]
self.right = point[0]
@accept_anything_as_vector
def set_center_left(self, point):
self.center_y = point[1]
self.left = point[0]
@accept_anything_as_vector
def set_center(self, point):
self.center_y = point[1]
self.center_x = point[0]
@accept_anything_as_vector
def set_center_right(self, point):
self.center_y = point[1]
self.right = point[0]
@accept_anything_as_vector
def set_bottom_left(self, point):
self.bottom = point[1]
self.left = point[0]
@accept_anything_as_vector
def set_bottom_center(self, point):
self.bottom = point[1]
self.center_x = point[0]
@accept_anything_as_vector
def set_bottom_right(self, point):
self.bottom = point[1]
self.right = point[0]
def set_vertices(self, vertices):
self.top_left = vertices[0]
self.top_right = vertices[1]
self.bottom_right = vertices[2]
self.bottom_left = vertices[3]
# Properties (fold)
left = property(get_left, set_left)
center_x = property(get_center_x, set_center_x)
right = property(get_right, set_right)
top = property(get_top, set_top)
center_y = property(get_center_y, set_center_y)
bottom = property(get_bottom, set_bottom)
width = property(get_width, set_width)
height = property(get_height, set_height)
half_width = property(get_half_width)
half_height = property(get_half_height)
size = property(get_size, set_size)
size_as_int = property(get_size_as_int)
top_left = property(get_top_left, set_top_left)
top_center = property(get_top_center, set_top_center)
top_right = property(get_top_right, set_top_right)
center_left = property(get_center_left, set_center_left)
center = property(get_center, set_center)
center_right = property(get_center_right, set_center_right)
bottom_left = property(get_bottom_left, set_bottom_left)
bottom_center = property(get_bottom_center, set_bottom_center)
bottom_right = property(get_bottom_right, set_bottom_right)
vertices = property(get_vertices, set_vertices)
dimensions = property(get_dimensions)
tuple = property(get_tuple)
Rect = Rectangle
def get_distance(a, b):
a = cast_anything_to_vector(a)
b = cast_anything_to_vector(b)
return a.get_distance(b)
def interpolate(a, b, num_points=3):
a = cast_anything_to_vector(a)
b = cast_anything_to_vector(b)
interpolation = [a]
steps = num_points - 1
assert steps >= 0
for step in range(1, steps):
v = a.get_interpolated(b, step/steps)
interpolation.append(v)
interpolation.append(b)
return interpolation
# Exceptions
class NullVectorError (Exception):
""" Thrown when an operation chokes on a null vector. """
pass
class VectorCastError (Exception):
""" Thrown when an inappropriate object is used as a vector. """
def __init__(self, object):
Exception.__init__(self, "Could not cast %s to vector." % type(object))
class RectangleCastError (Exception):
""" Thrown when an inappropriate object is used as a rectangle. """