Mercurial > rinkhals
comparison gamelib/misc.py @ 456:96dbf2c8506e
Factor position cache out into its own class, make Position more useful.
author | Jeremy Thurgood <firxen@gmail.com> |
---|---|
date | Mon, 23 Nov 2009 10:30:22 +0000 |
parents | 129de5883524 |
children | f84ad10a9625 |
comparison
equal
deleted
inserted
replaced
455:fef4b1686d6c | 456:96dbf2c8506e |
---|---|
7 from pgu.algo import getline | 7 from pgu.algo import getline |
8 | 8 |
9 import serializer | 9 import serializer |
10 | 10 |
11 class Position(serializer.Simplifiable): | 11 class Position(serializer.Simplifiable): |
12 """2D position / vector""" | 12 """2D/3D position / vector. Assumed immutable.""" |
13 | 13 |
14 SIMPLIFY = ['x', 'y', 'z'] | 14 SIMPLIFY = ['x', 'y', 'z'] |
15 | 15 |
16 def __init__(self, x, y, z=0): | 16 def __init__(self, x, y, z=0): |
17 self.x = x | 17 self.x = x |
18 self.y = y | 18 self.y = y |
19 self.z = z | 19 self.z = z |
20 | 20 |
21 def to_tile_tuple(self): | 21 def to_tile_tuple(self): |
22 return self.x, self.y | 22 return self.x, self.y |
23 | |
24 def to_3d_tuple(self): | |
25 return self.x, self.y, self.z | |
23 | 26 |
24 def dist(self, b): | 27 def dist(self, b): |
25 """Gives the distance to another position""" | 28 """Gives the distance to another position""" |
26 | 29 |
27 return max(abs(self.x - b.x), abs(self.y - b.y), abs(self.z - b.z)) | 30 return max(abs(self.x - b.x), abs(self.y - b.y), abs(self.z - b.z)) |
36 return self.x < b.x | 39 return self.x < b.x |
37 | 40 |
38 def right_of(self, b): | 41 def right_of(self, b): |
39 return self.x > b.x | 42 return self.x > b.x |
40 | 43 |
44 def __hash__(self): | |
45 return hash(self.to_3d_tuple()) | |
46 | |
41 def __eq__(self, b): | 47 def __eq__(self, b): |
42 return self.x == b.x and self.y == b.y and self.z == b.z | 48 return self.to_3d_tuple() == b.to_3d_tuple() |
49 | |
50 def __str__(self): | |
51 return "<Position: %s>" % (self.to_3d_tuple(),) | |
43 | 52 |
44 def intermediate_positions(self, b): | 53 def intermediate_positions(self, b): |
45 """Only operates in two dimensions.""" | 54 """Only operates in two dimensions.""" |
46 if max(abs(self.x - b.x), abs(self.y - b.y)) <= 1: | 55 if max(abs(self.x - b.x), abs(self.y - b.y)) <= 1: |
47 # pgu gets this case wrong on occasion. | 56 # pgu gets this case wrong on occasion. |
61 self.total = 0 | 70 self.total = 0 |
62 if weightings: | 71 if weightings: |
63 for item, weight in weightings: | 72 for item, weight in weightings: |
64 self.weightings.append((item, weight)) | 73 self.weightings.append((item, weight)) |
65 self.total += weight | 74 self.total += weight |
66 | 75 |
67 def choose(self): | 76 def choose(self): |
68 roll = random.uniform(0, self.total) | 77 roll = random.uniform(0, self.total) |
69 for item, weight in self.weightings: | 78 for item, weight in self.weightings: |
70 if roll < weight: | 79 if roll < weight: |
71 return item | 80 return item |