source: nagslang/game_object.py@ 160:0c9b0449485e

Last change on this file since 160:0c9b0449485e was 160:0c9b0449485e, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Consolidate image rendering stuff a bit.

File size: 10.2 KB
Line 
1import math
2
3import pygame
4import pymunk
5import pymunk.pygame_util
6
7from nagslang.constants import (
8 SWITCH_PUSHERS, COLLISION_TYPE_SWITCH, COLLISION_TYPE_BOX, ZORDER_LOW)
9from nagslang.options import options
10from nagslang.resources import resources
11
12
13class PuzzleGlue(object):
14 """Glue that holds bits of a puzzle together.
15 """
16 def __init__(self):
17 self._components = {}
18
19 def add_component(self, name, puzzler):
20 if not isinstance(puzzler, Puzzler):
21 puzzler = puzzler.puzzler
22 self._components[name] = puzzler
23 puzzler.set_glue(self)
24
25 def get_state_of(self, name):
26 return self._components[name].get_state()
27
28
29class Puzzler(object):
30 """Behaviour specific to a puzzle component.
31 """
32 def set_glue(self, glue):
33 self.glue = glue
34
35 def set_game_object(self, game_object):
36 self.game_object = game_object
37
38 def get_state(self):
39 raise NotImplementedError()
40
41
42class FloorSwitchPuzzler(Puzzler):
43 def get_state(self):
44 space = self.game_object.get_space()
45 for shape in space.shape_query(self.game_object.get_shape()):
46 if shape.collision_type in SWITCH_PUSHERS:
47 return True
48 return False
49
50
51class StateProxyPuzzler(Puzzler):
52 def __init__(self, state_source):
53 self._state_source = state_source
54
55 def get_state(self):
56 return self.glue.get_state_of(self._state_source)
57
58
59class StateLogicalAndPuzzler(Puzzler):
60 def __init__(self, *state_sources):
61 self._state_sources = state_sources
62
63 def get_state(self):
64 for state_source in self._state_sources:
65 if not self.glue.get_state_of(state_source):
66 return False
67 return True
68
69
70class Physicser(object):
71 def __init__(self, space):
72 self._space = space
73
74 def get_space(self):
75 return self._space
76
77 def set_game_object(self, game_object):
78 self.game_object = game_object
79
80 def get_shape(self):
81 raise NotImplementedError()
82
83 def add_to_space(self):
84 raise NotImplementedError()
85
86 def remove_from_space(self):
87 raise NotImplementedError()
88
89 def get_render_position(self, surface):
90 raise NotImplementedError()
91
92 def get_angle(self):
93 raise NotImplementedError()
94
95 def apply_impulse(self, j, r=(0, 0)):
96 raise NotImplementedError()
97
98
99class SingleShapePhysicser(Physicser):
100 def __init__(self, space, shape):
101 super(SingleShapePhysicser, self).__init__(space)
102 self._shape = shape
103
104 def get_shape(self):
105 return self._shape
106
107 def add_to_space(self):
108 self.get_space().add(self._shape)
109 if not self._shape.body.is_static:
110 self.get_space().add(self._shape.body)
111
112 def remove_from_space(self):
113 self.get_space().remove(self._shape)
114 if not self._shape.body.is_static:
115 self.get_space().remove(self._shape.body)
116
117 def get_render_position(self, surface):
118 pos = self._shape.body.position
119 return pymunk.pygame_util.to_pygame(pos, surface)
120
121 def get_angle(self):
122 return self._shape.body.angle
123
124 def apply_impulse(self, j, r=(0, 0)):
125 return self._shape.body.apply_impulse(j, r)
126
127
128class Renderer(object):
129 def set_game_object(self, game_object):
130 self.game_object = game_object
131
132 def _render_shape(self, surface):
133 shape = self.game_object.get_shape()
134 # Less general that pymunk.pygame_util.draw, but also a lot less noisy.
135 color = getattr(shape, 'color', pygame.color.THECOLORS['lightblue'])
136 # We only explicitly draw Circle and Poly shapes. Everything else we
137 # forward to pymunk.
138 if isinstance(shape, pymunk.Circle):
139 centre = pymunk.pygame_util.to_pygame(shape.body.position, surface)
140 radius = int(shape.radius)
141 pygame.draw.circle(surface, color, centre, radius, 2)
142 elif isinstance(shape, pymunk.Poly):
143 # polygon bounding box
144 points = [pymunk.pygame_util.to_pygame(p, surface)
145 for p in shape.get_vertices()]
146 pygame.draw.lines(surface, color, True, points, 2)
147 else:
148 pymunk.pygame_util.draw(surface, shape)
149
150 def render(self, surface):
151 if options.debug:
152 self._render_shape(surface)
153
154 def animate(self):
155 # Used by time animatations to advance the clock
156 pass
157
158
159def image_pos(image, pos):
160 return (pos[0] - image.get_width() / 2,
161 pos[1] - image.get_height() / 2)
162
163
164class ImageRenderer(Renderer):
165 def __init__(self, image):
166 self._image = image
167
168 def get_image(self):
169 return self._image
170
171 def rotate_image(self, image):
172 angle = self.game_object.get_render_angle() * 180 / math.pi
173 return pygame.transform.rotate(image, angle)
174
175 def render_image(self, surface, image):
176 image = self.rotate_image(image)
177 pos = self.game_object.get_render_position(surface)
178 surface.blit(image, image_pos(image, pos))
179
180 def render(self, surface):
181 self.render_image(surface, self.get_image())
182 super(ImageRenderer, self).render(surface)
183
184
185class FacingImageRenderer(ImageRenderer):
186 def __init__(self, left_image, right_image):
187 self._images = {
188 'left': left_image,
189 'right': right_image,
190 }
191 self._face = 'left'
192
193 def _update_facing(self, angle):
194 if abs(angle) < math.pi / 2:
195 self._face = 'right'
196 elif abs(angle) > math.pi / 2:
197 self._face = 'left'
198
199 def rotate_image(self, image):
200 # Facing images don't get rotated.
201 return image
202
203 def get_facing_image(self):
204 return self._images[self._face]
205
206 def get_image(self):
207 angle = self.game_object.get_render_angle()
208 self._update_facing(angle)
209 return self.get_facing_image()
210
211
212class AnimatedFacingImageRenderer(FacingImageRenderer):
213 def __init__(self, left_images, right_images):
214 self._images = {
215 'left': left_images,
216 'right': right_images,
217 }
218 self._frame = 0
219 self._moving = False
220 self._face = 'left'
221
222 def get_facing_image(self):
223 if self._frame >= len(self._images[self._face]):
224 self._frame = 0
225 return self._images[self._face][self._frame]
226
227 def animate(self):
228 if self._moving:
229 self._frame += 1
230 else:
231 self._frame = 0
232
233 def start(self):
234 self._moving = True
235
236 def stop(self):
237 self._moving = False
238
239
240class TimedAnimatedRenderer(ImageRenderer):
241
242 def __init__(self, images):
243 self._images = images
244 self._frame = 0
245 self._image = None
246
247 def get_image(self):
248 if self._frame > len(self._imaages):
249 self._frame = 0
250 return self._images[self._frame]
251
252 def animate(self):
253 self._frame += 1
254
255
256class ShapeRenderer(Renderer):
257 def render(self, surface):
258 self._render_shape(surface)
259 super(ShapeRenderer, self).render(surface)
260
261
262class ShapeStateRenderer(ShapeRenderer):
263 """Renders the shape in a different colour depending on the state.
264
265 Requires the game object it's attached to to have a puzzler.
266 """
267 def render(self, surface):
268 if self.game_object.puzzler.get_state():
269 color = pygame.color.THECOLORS['green']
270 else:
271 color = pygame.color.THECOLORS['red']
272
273 self.game_object.get_shape().color = color
274 super(ShapeStateRenderer, self).render(surface)
275
276
277def damping_velocity_func(body, gravity, damping, dt):
278 """Apply custom damping to this body's velocity.
279 """
280 damping = getattr(body, 'damping', damping)
281 return pymunk.Body.update_velocity(body, gravity, damping, dt)
282
283
284def make_body(mass, moment, position, damping=None):
285 body = pymunk.Body(mass, moment)
286 body.position = tuple(position)
287 if damping is not None:
288 body.damping = damping
289 body.velocity_func = damping_velocity_func
290 return body
291
292
293class GameObject(object):
294 """A representation of a thing in the game world.
295
296 This has a rendery thing, physicsy things and maybe some other things.
297 """
298
299 def __init__(self, physicser, renderer, puzzler=None):
300 self.physicser = physicser
301 physicser.set_game_object(self)
302 self.physicser.add_to_space()
303 self.renderer = renderer
304 renderer.set_game_object(self)
305 self.puzzler = puzzler
306 if puzzler is not None:
307 puzzler.set_game_object(self)
308 self.zorder = ZORDER_LOW
309
310 def get_space(self):
311 return self.physicser.get_space()
312
313 def get_shape(self):
314 return self.physicser.get_shape()
315
316 def get_render_position(self, surface):
317 return self.physicser.get_render_position(surface)
318
319 def get_render_angle(self):
320 return self.physicser.get_angle()
321
322 def render(self, surface):
323 return self.renderer.render(surface)
324
325 def animate(self):
326 self.renderer.animate()
327
328
329class FloorSwitch(GameObject):
330 def __init__(self, space, position):
331 body = make_body(None, None, position)
332 self.shape = pymunk.Circle(body, 30)
333 self.shape.collision_type = COLLISION_TYPE_SWITCH
334 self.shape.sensor = True
335 super(FloorSwitch, self).__init__(
336 SingleShapePhysicser(space, self.shape),
337 ShapeStateRenderer(),
338 FloorSwitchPuzzler(),
339 )
340
341
342class FloorLight(GameObject):
343 def __init__(self, space, position, state_source):
344 body = make_body(None, None, position)
345 self.shape = pymunk.Circle(body, 10)
346 self.shape.collision_type = COLLISION_TYPE_SWITCH
347 self.shape.sensor = True
348 super(FloorLight, self).__init__(
349 SingleShapePhysicser(space, self.shape),
350 ShapeStateRenderer(),
351 StateProxyPuzzler(state_source),
352 )
353
354
355class Box(GameObject):
356 def __init__(self, space, position):
357 body = make_body(10, 10000, position, damping=0.5)
358 self.shape = pymunk.Poly(
359 body, [(-20, -20), (20, -20), (20, 20), (-20, 20)])
360 self.shape.collision_type = COLLISION_TYPE_BOX
361 super(Box, self).__init__(
362 SingleShapePhysicser(space, self.shape),
363 ImageRenderer(resources.get_image('objects', 'crate.png')),
364 )
Note: See TracBrowser for help on using the repository browser.