File size: 3,070 Bytes
4b876a7 | 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 |
# TODO: Not complete yet, this is just a bunch of ideas
import math
class DrawableElement(object):
'''
Represents some polygon on the canvas that can move around and such
'''
def __init__(self, pts, center, angle, color):
self.color = color
self.pts = pts # list of (x,y)
self.center = center # (x,y)
self.angle = angle # radians
def initialize(self, canvas):
self.canvas = canvas
self.id = self.canvas.create_polygon(*self.pts, fill=self.color)
def intersects(self):
# TODO:
pass
def move(self, v):
'''v is a tuple of x/y coordinates to move object'''
# rotate movement vector according to the angle of the object
vx, vy = v
vx, vy = vx*math.cos(self.angle) - vy*math.sin(self.angle), \
vx*math.sin(self.angle) + vy*math.cos(self.angle)
def _move(xy):
x, y = xy
return x+vx, y+vy
# TODO: detect other objects in the way, stop movement appropriately
self.pts = [p for p in map(lambda x: _move(x), self.pts)]
self.center = _move(self.center)
def rotate(self, angle):
'''
This works. Rotates the object about its center.
'''
angle = math.radians(angle)
self.angle = (self.angle + angle) % (math.pi*2.0)
# precalculate these parameters
c = math.cos(angle)
s = math.sin(angle)
px, py = self.center
def _rotate_point(xy):
x, y = xy
x = x - px
y = y - py
return (x*c - y*s)+px, (x*s + y*c)+py
# calculate rotation for each point
self.pts = [p for p in map(lambda x: _rotate_point(x), self.pts)]
def set_color(self, color):
self.color = color
self.canvas.itemconfig(self.id, fill=color)
def update_coordinates(self):
# flatten the list of coordinates
if hasattr(self, 'canvas'):
pts = [c for p in self.pts for c in p]
self.canvas.coords(self.id, *pts)
class GameElement(object):
'''A game element can contain a number of drawable elements, and
all of them move at the same time, and deal with collisions and
such at the same time'''
def __init__(self):
self.elements = []
def initialize(self, canvas):
for e in self.elements:
e.initialize(canvas)
# TODO: I feel these may not be necessary?
def move(self, v):
for e in self.elements:
e.move(v)
def rotate(self, angle):
for e in self.elements:
e.rotate(angle)
def update_coordinates(self):
for e in self.elements:
e.update_coordinates()
|