Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 381b43f

Browse files
authoredDec 26, 2021
General cleanup and fixes
1 parent c4f1090 commit 381b43f

File tree

11 files changed

+233
-307
lines changed

11 files changed

+233
-307
lines changed
 

‎gameobjects/__init__.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
14
__all__ = [
2-
'vector2',
3-
'vector3',
4-
'util',
5-
'sphere',
6-
'matrix44',
7-
'color',
8-
'gametime',
9-
'grid'
5+
'vector2',
6+
'vector3',
7+
'util',
8+
'sphere',
9+
'matrix44',
10+
'color',
11+
'gametime',
12+
'grid'
1013
]
1114

12-
13-
__version__ = "0.0.3"
15+
__version__ = '0.0.3'

‎gameobjects/color.py

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,27 @@
1-
from math import *
2-
from util import format_number
3-
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# Color Module
44

5-
class ColorRGBA(object):
5+
"Color module"
66

7-
__slots__ = ('_c',)
7+
__title__ = 'color'
88

9+
from util import format_number
910

11+
class ColorRGBA:
12+
"Color with red, green, blue, and alpha components."
13+
__slots__ = ('_c',)
14+
1015
def __init__(self, *args):
11-
12-
"""Creates a color object."""
13-
16+
"Creates a color object."
17+
1418
if not args:
1519
self._c = [0.0, 0.0, 0.0, 1.0]
1620
return
17-
21+
1822
if len(args) == 1:
1923
args = args[0]
20-
24+
2125
if len(args) == 3:
2226
r, g, b = args
2327
self._c = [float(r), float(g), float(b), 1.0]
@@ -26,26 +30,23 @@ def __init__(self, *args):
2630
r, g, b, a = args
2731
self._c = [float(r), float(g), float(b), float(a)]
2832
return
29-
30-
raise ValueError("0, 1, 3 or 4 values required")
31-
33+
34+
raise ValueError('0, 1, 3 or 4 values required')
35+
3236
def __str__(self):
33-
34-
return "(" + ", ".join(format_number(c) for c in self._c) + ")"
37+
return '(' + ', '.join(format_number(c) for c in self._c) + ')'
3538
#return "(" + ", ".join(map(str, self._c)) + ")"
3639

3740
def __repr__(self):
38-
41+
3942
return "ColorRGBA(" + ", ".join(map(str, self._c)) + ")"
4043

4144
@classmethod
4245
def black(cls):
43-
44-
"""Create a color object representing black."""
45-
46-
c = cls.__new__(cls, object)
47-
c._c = [0.0, 0.0, 0.0, 1.0]
48-
return c
46+
"Create a color object representing black."
47+
self = cls.__new__(cls, object)
48+
self._c = [0.0, 0.0, 0.0, 1.0]
49+
return self
4950

5051
@classmethod
5152
def white(cls):
@@ -996,10 +997,7 @@ def mul_alpha(self):
996997
'lightgreen' : (0.564705882353, 0.933333333333, 0.564705882353),
997998
}
998999

999-
1000-
1001-
if __name__ == "__main__":
1002-
1000+
def test():
10031001
c1 = Color(.5, .2, .8)
10041002
c2 = Color(1., 0., .2)
10051003
print(c1)
@@ -1010,3 +1008,6 @@ def mul_alpha(self):
10101008
print(c1('rrrgggbbbaaa'))
10111009
print(Color.from_palette('magenta').rgba8)
10121010
#palette.red += palette.blue
1011+
1012+
if __name__ == "__main__":
1013+
test()

‎gameobjects/gametime.py

Lines changed: 34 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# Game Time Module
14

5+
"Game Time Module"
26

3-
class GameClock(object):
4-
5-
"""Manages time in a game."""
6-
7+
__title__ = "gametime"
8+
9+
import time as _time
10+
11+
class GameClock:
12+
"Manages time in a game."
713
def __init__(self, game_ticks_per_second=20):
8-
914
"""Create a Game Clock object.
1015
1116
game_ticks_per_second -- The number of logic frames a second.
1217
1318
"""
14-
19+
1520
self.game_ticks_per_second = float(game_ticks_per_second)
1621
self.game_tick = 1. / self.game_ticks_per_second
1722
self.speed = 1.
@@ -30,11 +35,10 @@ def __init__(self, game_ticks_per_second=20):
3035
self.fps_sample_start_time = 0.0
3136
self.fps_sample_count = 0
3237
self.average_fps = 0
33-
34-
38+
39+
3540
def start(self):
36-
37-
"""Starts the Game Clock. Must be called once."""
41+
"Starts the Game Clock. Must be called once."
3842

3943
if self.started:
4044
return
@@ -54,7 +58,6 @@ def start(self):
5458

5559

5660
def set_speed(self, speed):
57-
5861
"""Sets the speed of the clock.
5962
6063
speed -- A time factor (1 is normal speed, 2 is twice normal)
@@ -66,70 +69,53 @@ def set_speed(self, speed):
6669
raise ValueError("Negative speeds not supported")
6770

6871
self.speed = speed
69-
70-
72+
7173
def pause(self):
72-
73-
"""Pauses the Game Clock."""
74-
74+
"Pauses the Game Clock."
7575
self.pause = True
76-
76+
7777
def unpause(self):
78-
79-
"""Un-pauses the Game Clock."""
80-
78+
"Un-pauses the Game Clock."
8179
self.pause = False
82-
83-
80+
8481
def get_real_time(self):
85-
8682
"""Returns the real time, as reported by the system clock.
8783
This method may be overriden."""
88-
89-
import time
90-
return time.clock()
91-
92-
84+
85+
return _time.time()
86+
9387
def get_fps(self):
94-
9588
"""Retrieves the current frames per second as a tuple containing
9689
the fps and average fps over a second."""
97-
9890
return self.fps, self.average_fps
9991

100-
10192
def get_between_frame(self):
102-
10393
"""Returns the interpolant between the previous game tick and the
10494
next game tick."""
10595

10696
return self.between_frame
10797

108-
10998
def update(self, max_updates = 0):
110-
11199
"""Advances time, must be called once per frame. Yields tuples of
112100
game frame count and game time.
113101
114102
max_updates -- Maximum number of game time updates to issue.
115-
116103
"""
117104

118-
assert self.started, "You must call 'start' before using a GameClock."
119-
105+
assert self.started, "You must call 'start' before using a GameClock."
106+
120107
real_time_now = self.get_real_time()
121108

122109
self.real_time_passed = real_time_now - self.real_time
123110
self.real_time = real_time_now
124111

125112
self.clock_time += self.real_time_passed
126-
113+
127114
if not self.paused:
128115
self.virtual_time += self.real_time_passed * self.speed
129116

130117
update_count = 0
131-
while self.game_time + self.game_tick < self.virtual_time:
132-
118+
while self.game_time + self.game_tick < self.virtual_time:
133119
self.game_frame_count += 1
134120
self.game_time = self.game_frame_count * self.game_tick
135121
yield (self.game_frame_count, self.game_time)
@@ -138,7 +124,7 @@ def update(self, max_updates = 0):
138124
break
139125

140126
self.between_frame = ( self.virtual_time - self.game_time ) / self.game_tick
141-
127+
142128
if self.real_time_passed != 0:
143129
self.fps = 1.0 / self.real_time_passed
144130
else:
@@ -151,22 +137,19 @@ def update(self, max_updates = 0):
151137
self.average_fps = self.fps_sample_count / (self.real_time - self.fps_sample_start_time)
152138
self.fps_sample_start_time = self.real_time
153139
self.fps_sample_count = 0
154-
155-
156-
if __name__ == "__main__":
157-
158-
import time
140+
141+
def test():
159142
t = GameClock(20) # AI is 20 frames per second
160143
t.start()
161144

162145
while t.virtual_time < 2.0:
163-
164146
for (frame_count, game_time) in t.update():
165-
166147
print("Game frame #%i, %2.4f" % (frame_count, game_time))
167-
148+
168149
virtual_time = t.virtual_time
169150
print("\t%2.2f%% between game frame, time is %2.4f"%(t.between_frame*100., virtual_time))
170151

171-
172-
time.sleep(0.2) # Simulate time to render frame
152+
_time.sleep(0.2) # Simulate time to render frame
153+
154+
if __name__ == '__main__':
155+
test()

‎gameobjects/grid.py

Lines changed: 66 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# Grid Module
14

2-
from locals import WRAP_REPEAT, WRAP_CLAMP, WRAP_ERROR
3-
from util import saturate
5+
"Grid module"
6+
7+
__title__ = 'grid'
48

5-
class Grid(object):
9+
from locals import WRAP_REPEAT, WRAP_CLAMP, WRAP_ERROR, WRAP_NONE
10+
from util import saturate
611

12+
class Grid:
13+
"Grid class"
714
def __init__( self, node_factory,
815
width,
916
height,
1017
x_wrap = WRAP_ERROR,
1118
y_wrap = WRAP_ERROR ):
12-
19+
1320
"""Create a grid object.
1421
1522
node_factory -- Callable that takes the x and y coordinate of the node
@@ -35,203 +42,175 @@ def __init__( self, node_factory,
3542

3643
self._wrap_functions = [ self._make_wrap(self._x_wrap, self.width),
3744
self._make_wrap(self._y_wrap, self.height) ]
38-
39-
45+
4046
def _get_x_wrap(self):
4147
return self._x_wrap
4248
def _set_x_wrap(self, x_wrap):
4349
self._x_wrap = x_wrap
4450
self._wrap_functions[0] = self._make_wrap(x_wrap, self.width)
4551
x_wrap = property(_get_x_wrap, _set_x_wrap, None, "X wrap")
46-
52+
4753
def _get_y_wrap(self):
4854
return self._y_wrap
4955
def _set_y_wrap(self, y_wrap):
5056
self._y_wrap = y_wrap
5157
self._wrap_functions[1] = self._make_wrap(y_wrap, self.height)
5258
y_wrap = property(_get_y_wrap, _set_y_wrap, None, "Y wrap")
53-
54-
59+
5560
def _make_wrap(self, wrap, edge):
56-
5761
if wrap == WRAP_NONE:
5862
def do_wrap(value):
5963
return value
60-
64+
6165
elif wrap == WRAP_REPEAT:
6266
def do_wrap(value):
6367
return value % edge
64-
68+
6569
elif wrap == WRAP_CLAMP:
6670
def do_wrap(value):
6771
if value < 0:
6872
return 0
6973
if value >= edge:
7074
value = edge
7175
return value
72-
76+
7377
elif wrap == WRAP_ERROR:
7478
def do_wrap(value):
7579
if value < 0 or value >= edge:
76-
raise IndexError("coordinate out of range")
77-
80+
raise IndexError("Coordinate out of range")
81+
return value
7882
else:
7983
raise ValueError("Unknown wrap mode")
80-
84+
8185
return do_wrap
82-
83-
86+
8487
def wrap(self, coord):
85-
8688
x, y = coord
8789
wrap_x, wrap_y = self._wrap_functions
8890
return ( wrap_x(x), wrap_y(y) )
89-
90-
91+
9192
def wrap_x(self, x):
9293
"""Wraps an x coordinate.
9394
9495
x -- X Coordinate
9596
9697
"""
97-
98+
9899
return self._wrap_functions[0](x)
99-
100+
100101
def wrap_y(self, y):
101102
"""Wraps a y coordinate.
102103
103104
y -- Y Coordinate.
104105
105106
"""
106-
107+
107108
return self._wrap_functions[1](y)
108-
109-
109+
110110
def get_size(self):
111-
112-
"""Retrieves the size of the grid as a tuple (width, height)."""
113-
111+
"Retrieves the size of the grid as a tuple (width, height)."
114112
return self.width, self.height
115-
116-
113+
117114
def __getitem__(self, coord):
118-
119115
x, y = coord
120-
116+
121117
if isinstance(x, slice) or isinstance(y, slice):
122118
if isinstance(x, slice):
123119
x_indices = x.indices(self.width)
124120
else:
125121
x_indices = [x]
126-
122+
127123
if isinstance(y, slice):
128124
y_indices = y.indices(self.height)
129125
else:
130126
y_indices = [y]
131-
127+
132128
try:
133129
wrap_x, wrap_y = self._wrap_functions
134-
130+
135131
ret = []
136132

137133
for y_index in range(*y_indices):
138134
nodes_y = self.nodes[ wrap_y(y_index) ]
139-
135+
140136
for x_index in range(*x_indices):
141137
ret.append( nodes_y[ wrap_x(x_index) ] )
142-
143138
except IndexError:
144139
raise IndexError("Slice out of range")
145-
140+
146141
return ret
147-
148-
142+
149143
x, y = self.wrap(coord)
150-
144+
151145
if x < 0 or y < 0:
152-
raise IndexError("coordinate out of range")
153-
146+
raise IndexError("Coordinate out of range")
154147
try:
155148
return self.nodes[y][x]
156149
except IndexError:
157-
raise IndexError("coordinate out of range")
158-
159-
150+
raise IndexError("Coordinate out of range")
151+
160152
def __iter__(self):
161-
162153
for row in self.nodes:
163154
for node in row:
164155
yield node
165-
166-
156+
167157
def __contains__(self, value):
168-
169158
for row in self.nodes:
170159
if node in row:
171160
return True
172-
161+
173162
return False
174-
175-
163+
176164
def clear(self):
177-
178-
"""Resets the grid."""
179-
165+
"Resets the grid."
166+
180167
node_factory = self.node_factory
181-
168+
182169
self.nodes[:] = [ [node_factory(x, y) for x in range(width)] \
183170
for y in range(height)]
184-
185-
171+
186172
def get(self, coord, default=None):
187-
188173
"""Retrieves a node from the grid.
189174
190175
coord -- Coordinate to retrieve
191176
default -- Default value to use if coord is out of range
192177
193178
"""
194-
179+
195180
x, y = self.wrap(coord)
196-
181+
197182
if x < 0 or y < 0 or x >= self.width or y >= self.height:
198183
if default is not None:
199184
return default
200185
else:
201186
raise IndexError("coordinate out of range")
202-
187+
203188
return self.nodes[y][x]
204-
205-
189+
206190
def get_nodes(self, coord, size, wrap=False):
207-
208191
width = self.width
209192
height = self.height
210-
193+
211194
x1, y1 = coord
212195
x1 = saturate(x1, 0, width)
213196
y1 = saturate(y1, 0, height)
214197
w, h = size
215-
x2, y2 = (x+w, y+h)
216-
x = saturate(x, 0, width)
217-
y = saturate(y, 0, height)
218-
198+
x2, y2 = (x1+w, y1+h)
199+
x2 = saturate(x2, 0, width)
200+
y2 = saturate(y2, 0, height)
201+
219202
if x1 > x2:
220203
x1, x2 = x2, x1
221204
if y1 > y2:
222205
y1, y2 = y2, y1
223-
206+
224207
wrap_x, wrap_y = self._wrap_functions
225-
208+
226209
nodes = self.nodes
227210
return [self.nodes[y_coord][x1:x2] for y_coord in range(y1, y2)]
228211

229-
230-
231-
232-
if __name__ == "__main__":
233-
234-
class Square(object):
212+
def test():
213+
class Square:
235214
def __init__(self, x, y):
236215
self.coord = (x, y)
237216
def __str__(self):
@@ -240,9 +219,12 @@ def __repr__(self):
240219
return str(self.coord)
241220

242221
g = Grid(Square, 100, 100, x_wrap = WRAP_REPEAT)
243-
244-
for square in g:
245-
print(str(square))
246-
222+
##
223+
## for square in g:
224+
## print(str(square))
225+
247226
print(g[10:20, 10:20])
248227
print(g.get_nodes((-2, 0), (5, 5)))
228+
229+
if __name__ == '__main__':
230+
test()

‎gameobjects/locals.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22

33
( WRAP_REPEAT,
44
WRAP_CLAMP,
5-
WRAP_ERROR ) = range(3)
5+
WRAP_ERROR,
6+
WRAP_NONE ) = range(4)

‎gameobjects/sphere.py

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# Sphere Module
4+
5+
"Sphere module"
6+
7+
__title__ = 'sphere'
8+
19
import vector3
210
from util import format_number
311

4-
class Sphere(object):
12+
class Sphere:
13+
__slots__ = '_position', '_radius'
514

615
def __init__(self, position=(0,0,0), radius= 1.):
7-
816
self._position = vector3.Vector3(position)
917
self._radius = float(radius)
10-
11-
18+
1219
def get_position(self):
1320
return self._position
1421
def set_position(self, position):
@@ -20,51 +27,33 @@ def get_radius(self):
2027
def set_radius(self, radius):
2128
self._radius = float(radius)
2229
radius = property(get_radius, set_radius, None, "Radius of the sphere.")
23-
24-
25-
def __str__(self):
26-
27-
return "( position %s, radius %s )" % (self.position, format_number(self.radius))
2830

31+
def __str__(self):
32+
return 'f( position {self.position}, radius {format_number(self.radius)} )'
2933

3034
def __repr__(self):
31-
32-
return "Sphere(%s, %s)" % (tuple(self.position), self.radius)
33-
34-
35+
return f'Sphere({tuple(self.position)}, {self.radius})'
36+
3537
def __contains__(self, shape):
36-
37-
try:
38-
return shape.in_sphere(self)
39-
except AttributeError:
38+
if not hasattr(shape, 'in_sphere'):
4039
raise TypeError( "No 'in_sphere' method supplied by %s" % type(shape) )
41-
42-
40+
return shape.in_sphere(self)
41+
4342
def contains(self, shape):
44-
4543
return shape in self
46-
47-
44+
4845
def in_sphere(self, sphere):
49-
5046
return self.position.get_distance(sphere.position) + self.radius <= sphere.radius
51-
52-
47+
5348
def intersects(self, shape):
54-
55-
try:
56-
return shape.intersects_sphere(self)
57-
except AttributeError:
49+
if not hasattr(shape, 'intersects_sphere'):
5850
raise TypeError( "No 'intersects_sphere' method supplied by %s" % type(shape) )
59-
51+
return shape.intersects_sphere(self)
6052

6153
def intersects_sphere(self, sphere):
62-
6354
return self.position.get_distance(sphere.position) < self.radius + sphere.radius
64-
6555

6656
if __name__ == "__main__":
67-
6857
s1 = Sphere()
6958
s2 = Sphere( (1,1,1) )
7059
s3 = Sphere( radius=10 )
@@ -79,7 +68,7 @@ def intersects_sphere(self, sphere):
7968

8069
big = Sphere(radius=1)
8170
small = Sphere(position=(.8, 0, 0), radius=.2)
82-
71+
8372

8473
print(small, big)
8574
print(small in big)

‎gameobjects/test_vector3.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
14
import unittest
25

36
from vector3 import Vector3
47

58
class TestVector3(unittest.TestCase):
6-
79
def test_add(self):
810
v1 = Vector3(1, 2, 3)
911
v2 = Vector3(4, 5, 6)
1012
self.assertEqual(v1+v2, (5, 7, 9))
1113
self.assertEqual((1, 2, 3)+v2, (5, 7, 9))
12-
13-
14+
1415
def test_sub(self):
1516
v1 = Vector3(1, 2, 3)
1617
v2 = Vector3(4, 5, 6)
1718
self.assertEqual(v1-v2, (-3, -3, -3))
1819
self.assertEqual((1, 2, 3)-v2, (-3, -3, -3))
19-
20-
20+
2121
def test_mul(self):
2222
v1 = Vector3(1, 2, 3)
2323
v2 = Vector3(4, 5, 6)
@@ -27,7 +27,7 @@ def test_mul(self):
2727
self.assertEqual(v1*(3, 3, 3), (3, 6, 9))
2828
v1 *= 2
2929
self.assertEqual(v1, (2, 4, 6))
30-
30+
3131
def test_div(self):
3232
v1 = Vector3(1, 2, 3)
3333
v2 = Vector3(4, 5, 6)
@@ -37,19 +37,19 @@ def test_div(self):
3737
self.assertEqual(v1/(3, 3, 3), (1./3, 2/3., 3/3.))
3838
v1 /= 2
3939
self.assertEqual(v1, (.5, 1., 1.5))
40-
40+
4141
def test_length(self):
4242
v1 = Vector3(3., 4., 0.)
4343
self.assertEqual(v1.length, 5.)
4444
v1.length = 10.
4545
self.assertEqual(v1, (6, 8, 0))
4646
v1.normalise()
47-
assert(v1.length, 1.)
48-
47+
self.assertEqual(v1.length, 1.)
48+
4949
def test_copy(self):
5050
v1 = Vector3(3., 4., 0.)
51-
assert(v1.copy(), (3, 4, 0))
52-
51+
self.assertEqual(v1.copy(), (3, 4, 0))
52+
5353
def test_properties(self):
5454
v1 = Vector3(1, 2, 3)
5555
self.assertEqual(v1.x, 1)
@@ -61,7 +61,7 @@ def test_properties(self):
6161
self.assertEqual(v1.x, 2)
6262
self.assertEqual(v1.y, 4)
6363
self.assertEqual(v1.z, 6)
64-
64+
6565
def test_swizzle(self):
6666
v1 = Vector3(1, 2, 3)
6767
self.assertEqual(v1('xxxyyyzzz'), (1, 1, 1, 2, 2, 2, 3, 3, 3))

‎gameobjects/util.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,56 @@
1-
from math import *
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# Utils module
4+
5+
"Util module"
6+
7+
__title__ = 'util'
8+
9+
import math
210

311
def format_number(n, accuracy=6):
412
"""Formats a number in a friendly manner
513
(removes trailing zeros and unneccesary point."""
6-
7-
fs = "%."+str(accuracy)+"f"
8-
str_n = fs%float(n)
14+
15+
fs = f'%.{accuracy}f'
16+
str_n = fs % (float(n) + 0)# convert -0 to 0
917
if '.' in str_n:
1018
str_n = str_n.rstrip('0').rstrip('.')
11-
if str_n == "-0":
12-
str_n = "0"
13-
#str_n = str_n.replace("-0", "0")
1419
return str_n
1520

16-
1721
def lerp(a, b, i):
18-
"""Linear enterpolate from a to b."""
22+
"Linear enterpolate from a to b."
1923
return a+(b-a)*i
2024

21-
2225
def range2d(range_x, range_y):
23-
24-
"""Creates a 2D range."""
25-
26+
"Creates a 2D range."
2627
range_x = list(range_x)
2728
return [ (x, y) for y in range_y for x in range_x ]
2829

29-
3030
def xrange2d(range_x, range_y):
31-
32-
"""Iterates over a 2D range."""
33-
31+
"Iterates over a 2D range."
3432
range_x = list(range_x)
3533
for y in range_y:
3634
for x in range_x:
3735
yield (x, y)
3836

39-
4037
def saturate(value, low, high):
38+
"Ensure value is within bounds, min of low, max of high."
4139
return min(max(value, low), high)
4240

43-
4441
def is_power_of_2(n):
45-
"""Returns True if a value is a power of 2."""
46-
return log(n, 2) % 1.0 == 0.0
47-
42+
"Returns True if a value is a power of 2."
43+
return not math.log(n, 2) % 1
4844

4945
def next_power_of_2(n):
50-
"""Returns the next power of 2 that is >= n"""
51-
return int(2 ** ceil(log(n, 2)))
52-
53-
if __name__ == "__main__":
46+
"Returns the next power of 2 that is >= n"
47+
return int(2 ** math.ceil(math.log(n, 2)))
5448

49+
if __name__ == '__main__':
5550
print(list( xrange2d(range(3), range(3)) ))
5651
print(range2d(range(3), range(3)))
5752
print(is_power_of_2(7))
5853
print(is_power_of_2(8))
5954
print(is_power_of_2(9))
60-
55+
6156
print(next_power_of_2(7))

‎gameobjects/vector.py

Lines changed: 11 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,12 @@
22
# -*- coding: utf-8 -*-
33
# Vector Module
44

5-
"Vector module"
5+
"Game objects Vector module"
66

77
# Programmed by CoolCat467
88

9-
__title__ = 'Vector'
9+
__title__ = 'Game objects Vector'
1010
__author__ = 'CoolCat467'
11-
__version__ = '0.0.0'
12-
_ver_major__ = 0
13-
_ver_minor__ = 0
14-
_ver_patch__ = 0
1511

1612
import math
1713
from functools import wraps
@@ -25,7 +21,6 @@ def wrapped_op(self, rhs, *args, **kwargs):
2521
return function(self, rhs, *args, **kwargs)
2622
raise TypeError('Operand length is not same as own')
2723
return function(self, [rhs]*len(self), *args, **kwargs)
28-
## raise AttributeError('Operand has no length attribute')
2924
return wrapped_op
3025

3126
def simpleop(function):
@@ -86,11 +81,9 @@ def __init__(self, *args, dims=None, dtype=tuple):
8681
if not hasattr(dtype, '__getitem__'):
8782
raise TypeError('Data type class is not subscriptable!')
8883
if dims is None:
89-
## self._v = tuple(args)
9084
self._v = self.dtype(args)
9185
else:
9286
args = args[:dims]
93-
## self._v = tuple(list(args) + [0]*(dims-len(args)))
9487
self._v = self.dtype(list(args) + [0]*(dims-len(args)))
9588

9689
def __repr__(self):
@@ -150,9 +143,7 @@ def reverse(self):
150143
def normalize(self):
151144
"Normalize this vector."
152145
mag = self.magnitude
153-
## self._v = tuple(map(lambda x:x/mag, self._v))
154146
self._v = self.dtype(map(lambda x:x/mag, self._v))
155-
## self._v = list(map(lambda x:x/mag, self._v))
156147
return self
157148

158149
def normalized(self):
@@ -234,30 +225,12 @@ def __rpow__(self, lhs):
234225
@boolop('all')
235226
def __eq__(self, rhs):
236227
return self == rhs
237-
## return self._v == rhs
238228

239229
@vmathop
240230
@boolop('any')
241231
def __ne__(self, rhs):
242232
print((self, '!=', rhs))
243233
return self != rhs
244-
## return self._v != rhs
245-
246-
## @vmagop
247-
## def __gt__(x, y):
248-
## return x > y
249-
##
250-
## @vmagop
251-
## def _ge__(x, y):
252-
## return x >= y
253-
##
254-
## @vmagop
255-
## def __lt__(x, y):
256-
## return x < y
257-
##
258-
## @vmagop
259-
## def __le__(x, y):
260-
## return x <= y
261234

262235
def __hash__(self):
263236
return hash(self._v)
@@ -269,7 +242,7 @@ def set_length(self, new_length):
269242
mag = 0
270243
else:
271244
mag = new_length / cmag
272-
## self._v = (self * ([mag]*len(self)))._v
245+
## self._v = (self * mag)._v
273246
return self * mag
274247

275248
@onlylen(3)
@@ -299,14 +272,14 @@ class Vector1(Vector):
299272
"Vector1. Same as Vector, but stuck being 1d and has x attribute."
300273
_gameobjects_vector = 1
301274
def __init__(self, x=0, **kwargs):
302-
## kwargs['dims'] = 1
275+
kwargs['dims'] = 1
303276
if not 'dtype' in kwargs:
304277
kwargs['dtype'] = list
305278
super().__init__(x, **kwargs)
306279

307280
@classmethod
308281
def from_iter(cls, iterable, dtype=list):
309-
"Return Vector2 from iterable."
282+
"Return Vector1 from iterable."
310283
nxt = iter(iterable).__next__
311284
return cls(nxt(), dtype=dtype)
312285

@@ -389,6 +362,7 @@ def get_normalised(self):
389362
def get_distance_to(self, point):
390363
"Return distance to point"
391364
return (point - self).magnitude
365+
get_distance = get_distance_to
392366

393367
def set(self, *args):
394368
for idx, val in enumerate(args):
@@ -398,7 +372,6 @@ def set(self, *args):
398372

399373
def scalar_mul(self, scalar):
400374
self.__imul__(scalar)
401-
## return self *= scalar
402375
return self
403376
vector_mul = scalar_mul
404377

@@ -407,7 +380,6 @@ def get_scalar_mul(self, scalar):
407380
get_vector_mul = get_scalar_mul
408381

409382
def scalar_div(self, scalar):
410-
## return self /= scalar
411383
self.__idiv__(scalar)
412384
return self
413385
vector_div = scalar_div
@@ -427,7 +399,7 @@ class Vector2(Vector1):
427399
"Vector2. Same as Vector, but stuck being 2d and has x and y attributes."
428400
_gameobjects_vector = 2
429401
def __init__(self, x=0, y=0, **kwargs):
430-
## kwargs['dims'] = 2
402+
kwargs['dims'] = 2
431403
if not 'dtype' in kwargs:
432404
kwargs['dtype'] = list
433405
Vector.__init__(self, x, y, **kwargs)
@@ -450,14 +422,14 @@ class Vector3(Vector2):
450422
"Vector3. Same as Vector, but stuck being 3d and has x, y, and z attributes."
451423
_gameobjects_vector = 3
452424
def __init__(self, x=0, y=0, z=0, **kwargs):
453-
## kwargs['dims'] = 3
425+
kwargs['dims'] = 3
454426
if not 'dtype' in kwargs:
455427
kwargs['dtype'] = list
456428
Vector.__init__(self, x, y, z, **kwargs)
457429

458430
@classmethod
459431
def from_iter(cls, iterable, dtype=list):
460-
"Return Vector2 from iterable."
432+
"Return Vector3 from iterable."
461433
nxt = iter(iterable).__next__
462434
return cls(nxt(), nxt(), nxt(), dtype=dtype)
463435

@@ -473,14 +445,14 @@ class Vector4(Vector3):
473445
"Vector4. Same as Vector, but stuck being 4d and has x, y, z, and w attributes."
474446
_gameobjects_vector = 4
475447
def __init__(self, x=0, y=0, z=0, w=0, **kwargs):
476-
## kwargs['dims'] = 4
448+
kwargs['dims'] = 4
477449
if not 'dtype' in kwargs:
478450
kwargs['dtype'] = list
479451
Vector.__init__(self, x, y, z, w, **kwargs)
480452

481453
@classmethod
482454
def from_iter(cls, iterable, dtype=list):
483-
"Return Vector2 from iterable."
455+
"Return Vector4 from iterable."
484456
nxt = iter(iterable).__next__
485457
return cls(nxt(), nxt(), nxt(), nxt(), dtype=dtype)
486458

‎gameobjects/vector2.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
from math import sqrt
2-
from util import format_number
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
33

44
from vector import Vector2
55

6-
if __name__ == "__main__":
7-
6+
if __name__ == '__main__':
87
v1 = Vector2(1, 2)
98
print(v1('yx'))
109
print(Vector2.from_points((5,5), (10,10)))

‎gameobjects/vector3.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import math
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
"Vector3 module"
5+
6+
__title__ = 'vector3'
7+
8+
from math import sqrt
29
from util import format_number
310

411
from vector import Vector3 as _Vector3
@@ -21,28 +28,24 @@ def distance3d_squared(p1, p2):
2128

2229
return dx*dx + dy*dy +dz*dz
2330

24-
2531
def distance3d(p1, p2):
26-
2732
x, y, z = p1
2833
xx, yy, zz = p2
2934
dx = x - xx
3035
dy = y - yy
3136
dz = z - zz
3237

33-
return math.sqrt(dx*dx + dy*dy +dz*dz)
38+
return sqrt(dx*dx + dy*dy +dz*dz)
3439

3540
def centre_point3d(points):
36-
3741
return sum( Vector3.from_iter(p) for p in points ) / len(points)
3842

39-
4043
def test():
4144
v1 = Vector3(2.2323, 3.43242, 1.)
42-
45+
4346
print(3*v1)
4447
print((2, 4, 6)*v1)
45-
48+
4649
print((1, 2, 3)+v1)
4750
print(v1('xxxyyyzzz'))
4851
print(v1[2])
@@ -55,25 +58,24 @@ def test():
5558
print(v1.get_length())
5659
print(repr(v1))
5760
print(v1[1])
58-
61+
5962
p1 = Vector3(1,2,3)
6063
print(p1)
6164
print(repr(p1))
62-
65+
6366
for v in p1:
6467
print(v)
65-
66-
#print p1[6]
67-
68+
69+
#print(p1[6])
70+
6871
ptest = Vector3( [1,2,3] )
6972
print(ptest)
70-
73+
7174
z = Vector3()
7275
print(z)
7376

74-
file = open
75-
file("test.txt", "w").write( "\n".join(str(float(n)) for n in range(20)) )
76-
f = map(float, file("test.txt").read().splitlines())
77+
open("test.txt", "w").write( "\n".join(str(float(n)) for n in range(20)) )
78+
f = map(float, open("test.txt").read().splitlines())
7779
v1 = Vector3.from_iter( f )
7880
v2 = Vector3.from_iter( f )
7981
v3 = Vector3.from_iter( f )
@@ -90,9 +92,9 @@ def test():
9092
#print(tuple(ptest))
9193
#p1.set( (4, 5, 6) )
9294
#print(p1)
93-
95+
9496
print(Vector3(10,10,30)+v1)
95-
97+
9698
print(Vector3((0,0,0,1)))
9799

98100
print(Vector3(1, 2, 3).scale(3))

0 commit comments

Comments
 (0)
Please sign in to comment.