source: nagslang/game_object.py@ 477:290cb3a0927e

Last change on this file since 477:290cb3a0927e was 477:290cb3a0927e, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Extra helper

File size: 23.4 KB
Line 
1import pymunk
2import pymunk.pygame_util
3
4import math
5
6from nagslang import environment
7from nagslang import puzzle
8from nagslang import render
9from nagslang.mutators import FLIP_H, ImageOverlay
10from nagslang.constants import (
11 COLLISION_TYPE_DOOR, COLLISION_TYPE_FURNITURE, COLLISION_TYPE_PROJECTILE,
12 COLLISION_TYPE_SWITCH, COLLISION_TYPE_SHEEP, COLLISION_TYPE_SHEEP_PEN,
13 COLLISION_TYPE_WEREWOLF_ATTACK, SWITCH_PUSHERS, ZORDER_FLOOR, ZORDER_LOW,
14 ZORDER_HIGH)
15from nagslang.resources import resources
16from nagslang.events import DoorEvent
17
18
19class Result(object):
20 '''
21 Return from an update() function, to add new objects to the world, and/or
22 remove old objects.
23 '''
24 def __init__(self, add=(), remove=()):
25 self.add = add
26 self.remove = remove
27
28 def merge(self, result):
29 if result is not None:
30 self.add += result.add
31 self.remove += result.remove
32 return self
33
34
35def get_editable_game_objects():
36 classes = []
37 for cls_name, cls in globals().iteritems():
38 if isinstance(cls, type) and hasattr(cls, 'requires'):
39 classes.append((cls_name, cls))
40 return classes
41
42
43class Physicser(object):
44 def __init__(self, space):
45 self._space = space
46
47 def get_space(self):
48 return self._space
49
50 def set_space(self, new_space):
51 self._space = new_space
52
53 def set_game_object(self, game_object):
54 self.game_object = game_object
55
56 def get_shape(self):
57 raise NotImplementedError()
58
59 def add_to_space(self):
60 shape = self.get_shape()
61 self.get_space().add(shape)
62 if not shape.body.is_static:
63 self.get_space().add(shape.body)
64
65 def remove_from_space(self):
66 shape = self.get_shape()
67 self.get_space().remove(shape)
68 if not shape.body.is_static:
69 self.get_space().remove(shape.body)
70
71 def get_render_position(self, surface):
72 pos = self.get_shape().body.position
73 return pymunk.pygame_util.to_pygame(pos, surface)
74
75 def get_angle(self):
76 return self.get_shape().body.angle
77
78 def get_velocity(self):
79 return self.get_shape().body.velocity
80
81 def _get_position(self):
82 return self.get_shape().body.position
83
84 def _set_position(self, position):
85 self.get_shape().body.position = position
86
87 position = property(_get_position, _set_position)
88
89 def apply_impulse(self, j, r=(0, 0)):
90 return self.get_shape().body.apply_impulse(j, r)
91
92
93class SingleShapePhysicser(Physicser):
94 def __init__(self, space, shape):
95 super(SingleShapePhysicser, self).__init__(space)
96 self._shape = shape
97 shape.physicser = self
98
99 def get_shape(self):
100 return self._shape
101
102
103class MultiShapePhysicser(Physicser):
104 def __init__(self, space, shape, *extra_shapes):
105 super(MultiShapePhysicser, self).__init__(space)
106 self._shape = shape
107 self._extra_shapes = extra_shapes
108 shape.physicser = self
109
110 def get_shape(self):
111 return self._shape
112
113 def add_to_space(self):
114 shape = self.get_shape()
115 self.get_space().add(shape)
116 if not shape.body.is_static:
117 self.get_space().add(shape.body)
118 for s in self._extra_shapes:
119 self.get_space().add(s)
120
121 def remove_from_space(self):
122 shape = self.get_shape()
123 self.get_space().remove(shape)
124 if not shape.body.is_static:
125 self.get_space().remove(shape.body)
126 for s in self._extra_shapes:
127 self.get_space().remove(s)
128
129
130def damping_velocity_func(body, gravity, damping, dt):
131 """Apply custom damping to this body's velocity.
132 """
133 damping = getattr(body, 'damping', damping)
134 return pymunk.Body.update_velocity(body, gravity, damping, dt)
135
136
137def make_body(mass, moment, position, damping=None):
138 body = pymunk.Body(mass, moment)
139 body.position = tuple(position)
140 if damping is not None:
141 body.damping = damping
142 body.velocity_func = damping_velocity_func
143 return body
144
145
146class GameObject(object):
147 """A representation of a thing in the game world.
148
149 This has a rendery thing, physicsy things and maybe some other things.
150 """
151
152 zorder = ZORDER_LOW
153 is_moving = False # `True` if a movement animation should play.
154
155 def __init__(self, physicser, renderer, puzzler=None, overlay=None,
156 interactible=None):
157 self.lifetime = 0
158 self.physicser = physicser
159 physicser.set_game_object(self)
160 self.physicser.add_to_space()
161 self.renderer = renderer
162 renderer.set_game_object(self)
163 self.puzzler = puzzler
164 if puzzler is not None:
165 puzzler.set_game_object(self)
166 self.overlay = overlay
167 if overlay is not None:
168 self.overlay.set_game_object(self)
169 self.interactible = interactible
170 if interactible is not None:
171 self.interactible.set_game_object(self)
172 self._timers = {}
173 self._active_timers = {}
174
175 def add_timer(self, name, secs):
176 self._timers[name] = secs
177
178 def start_timer(self, name, secs=None):
179 if secs is None:
180 secs = self._timers[name]
181 self._active_timers[name] = secs
182
183 def check_timer(self, name):
184 return name in self._active_timers
185
186 def set_stored_state_dict(self, stored_state):
187 """Override this to set up whatever state storage you want.
188
189 The `stored_state` dict passed in contains whatever saved state we
190 might have for this object. If the return value of this method
191 evaluates to `True`, the contents of the `stored_state` dict will be
192 saved, otherwise it will be discarded.
193 """
194 pass
195
196 def get_space(self):
197 return self.physicser.get_space()
198
199 def get_shape(self):
200 return self.physicser.get_shape()
201
202 def get_render_position(self, surface):
203 return self.physicser.get_render_position(surface)
204
205 def get_render_angle(self):
206 return self.physicser.get_angle()
207
208 def get_facing_direction(self):
209 """Used by rendererd that care what direction an object is facing.
210 """
211 return None
212
213 def render(self, surface):
214 return self.renderer.render(surface)
215
216 def update(self, dt):
217 self.lifetime += dt
218 for timer in self._active_timers.keys():
219 self._active_timers[timer] -= dt
220 if self._active_timers[timer] <= 0:
221 self._active_timers.pop(timer)
222 self.renderer.update(dt)
223
224 def hit(self, weapon):
225 '''Was hit with a weapon (such as a bullet)'''
226 pass
227
228 def collide_with_protagonist(self, protagonist):
229 """Called as a `pre_solve` collision callback with the protagonist.
230
231 You can return `False` to ignore the collision, anything else
232 (including `None`) to process the collision as normal.
233 """
234 return True
235
236 def collide_with_furniture(self, furniture):
237 return True
238
239 def collide_with_claw_attack(self, claw_attack):
240 return True
241
242 def environmental_movement(self, vec):
243 self.physicser.apply_impulse(vec)
244
245 @classmethod
246 def requires(cls):
247 """Hints for the level editor"""
248 return [("name", "string")]
249
250 @classmethod
251 def movable(cls):
252 # Are we movable
253 hints = cls.requires()
254 for x in hints:
255 if 'position' in x:
256 return True
257 return False
258
259
260class FloorSwitch(GameObject):
261 zorder = ZORDER_FLOOR
262
263 def __init__(self, space, position):
264 body = make_body(None, None, position)
265 self.shape = pymunk.Circle(body, 30)
266 self.shape.collision_type = COLLISION_TYPE_SWITCH
267 self.shape.sensor = True
268 super(FloorSwitch, self).__init__(
269 SingleShapePhysicser(space, self.shape),
270 render.ImageStateRenderer({
271 True: resources.get_image('objects', 'sensor_on.png'),
272 False: resources.get_image('objects', 'sensor_off.png'),
273 }),
274 puzzle.CollidePuzzler(*SWITCH_PUSHERS),
275 )
276
277 @classmethod
278 def requires(cls):
279 return [("name", "string"), ("position", "coordinates")]
280
281
282class Note(GameObject):
283 zorder = ZORDER_FLOOR
284
285 def __init__(self, space, position, message):
286 body = make_body(None, None, position)
287 self.shape = pymunk.Circle(body, 30)
288 self.shape.sensor = True
289 super(Note, self).__init__(
290 SingleShapePhysicser(space, self.shape),
291 render.ImageRenderer(resources.get_image('objects', 'note.png')),
292 puzzle.CollidePuzzler(),
293 render.TextOverlay(message),
294 )
295
296 @classmethod
297 def requires(cls):
298 return [("name", "string"), ("position", "coordinates"),
299 ("message", "text")]
300
301
302class FloorLight(GameObject):
303 zorder = ZORDER_FLOOR
304
305 def __init__(self, space, position, state_source):
306 body = make_body(None, None, position)
307 self.shape = pymunk.Circle(body, 10)
308 self.shape.collision_type = COLLISION_TYPE_SWITCH
309 self.shape.sensor = True
310 super(FloorLight, self).__init__(
311 SingleShapePhysicser(space, self.shape),
312 render.ImageStateRenderer({
313 True: resources.get_image('objects', 'light_on.png'),
314 False: resources.get_image('objects', 'light_off.png'),
315 }),
316 puzzle.StateProxyPuzzler(state_source),
317 )
318
319 @classmethod
320 def requires(cls):
321 return [("name", "string"), ("position", "coordinates"),
322 ("state_source", "puzzler")]
323
324
325class Box(GameObject):
326 def __init__(self, space, position):
327 body = make_body(10, 10000, position, damping=0.5)
328 self.shape = pymunk.Poly(
329 body, [(-20, -20), (20, -20), (20, 20), (-20, 20)])
330 self.shape.friction = 0.5
331 self.shape.collision_type = COLLISION_TYPE_FURNITURE
332 super(Box, self).__init__(
333 SingleShapePhysicser(space, self.shape),
334 render.ImageRenderer(resources.get_image('objects', 'crate.png')),
335 )
336
337 @classmethod
338 def requires(cls):
339 return [("name", "string"), ("position", "coordinates"),
340 ("state_source", "puzzler")]
341
342
343class BaseDoor(GameObject):
344 zorder = ZORDER_FLOOR
345 is_open = True
346
347 def __init__(self, space, position, destination, dest_pos, angle,
348 renderer, condition):
349 body = make_body(pymunk.inf, pymunk.inf, position, damping=0.5)
350 self.shape = pymunk.Circle(body, 30)
351 self.shape.collision_type = COLLISION_TYPE_DOOR
352 self.shape.body.angle = float(angle) / 180 * math.pi
353 self.shape.sensor = True
354 self.destination = destination
355 self.dest_pos = tuple(dest_pos)
356 super(BaseDoor, self).__init__(
357 SingleShapePhysicser(space, self.shape),
358 renderer,
359 puzzle.ParentAttrPuzzler('is_open'),
360 interactible=environment.Interactible(
361 environment.Action(self._post_door_event, condition)),
362 )
363
364 def _post_door_event(self, protagonist):
365 DoorEvent.post(self.destination, self.dest_pos)
366
367
368class Door(BaseDoor):
369 def __init__(self, space, position, destination, dest_pos, angle):
370 super(Door, self).__init__(
371 space, position, destination, dest_pos, angle,
372 render.ImageRenderer(resources.get_image('objects', 'door.png')),
373 environment.YesCondition(),
374 )
375
376 @classmethod
377 def requires(cls):
378 return [("name", "string"), ("position", "coordinates"),
379 ("destination", "level name"), ("dest_pos", "coordinate"),
380 ("angle", "degrees")]
381
382
383class RestartGameDoor(Door):
384 def _post_door_event(self, protagonist):
385 protagonist.world.reset()
386 super(RestartGameDoor, self)._post_door_event(protagonist)
387
388
389class ContinueGameDoor(Door):
390 def _post_door_event(self, protagonist):
391 world = protagonist.world
392 DoorEvent.post(world.level[0], world.level[1])
393
394
395class PuzzleDoor(BaseDoor):
396 def __init__(self, space, position, destination, dest_pos, angle,
397 key_state):
398 self._key_state = key_state
399 overlay = ImageOverlay(resources.get_image('objects', 'lock.png'))
400 super(PuzzleDoor, self).__init__(
401 space, position, destination, dest_pos, angle,
402 render.ImageStateRenderer({
403 True: resources.get_image('objects', 'door.png'),
404 False: resources.get_image(
405 'objects', 'door.png', transforms=(overlay,)),
406 }),
407 environment.FunctionCondition(lambda p: self.is_open),
408 )
409
410 @property
411 def is_open(self):
412 return self._stored_state['is_open']
413
414 def set_stored_state_dict(self, stored_state):
415 self._stored_state = stored_state
416 self._stored_state.setdefault('is_open', False)
417 return True
418
419 def update(self, dt):
420 if not self.is_open:
421 self._stored_state['is_open'] = self.puzzler.glue.get_state_of(
422 self._key_state)
423 super(PuzzleDoor, self).update(dt)
424
425 @classmethod
426 def requires(cls):
427 return [("name", "string"), ("position", "coordinates"),
428 ("destination", "level name"), ("dest_pos", "coordinate"),
429 ("angle", "degrees"),
430 ("key_state", "puzzler")]
431
432
433class KeyedDoor(BaseDoor):
434 def __init__(self, space, position, destination, dest_pos, angle,
435 key_item=None):
436 self._key_item = key_item
437 overlay = ImageOverlay(
438 resources.get_image('objects', '%s.png' % (key_item,)))
439 super(KeyedDoor, self).__init__(
440 space, position, destination, dest_pos, angle,
441 render.ImageRenderer(resources.get_image(
442 'objects', 'door.png', transforms=(overlay,))),
443 environment.ItemRequiredCondition(key_item),
444 )
445
446 @classmethod
447 def requires(cls):
448 return [("name", "string"), ("position", "coordinates"),
449 ("destination", "level name"), ("dest_pos", "coordinate"),
450 ("angle", "degrees"), ("key_item", "item name")]
451
452
453class Bulkhead(GameObject):
454 zorder = ZORDER_FLOOR
455
456 def __init__(self, space, end1, end2, key_state=None):
457 body = make_body(None, None, (0, 0))
458 self.shape = pymunk.Segment(body, tuple(end1), tuple(end2), 3)
459 self.shape.collision_type = COLLISION_TYPE_DOOR
460 if key_state is None:
461 puzzler = puzzle.YesPuzzler()
462 else:
463 puzzler = puzzle.StateProxyPuzzler(key_state)
464 super(Bulkhead, self).__init__(
465 SingleShapePhysicser(space, self.shape),
466 render.BulkheadRenderer(),
467 puzzler,
468 )
469
470 def collide_with_protagonist(self, protagonist):
471 if self.puzzler.get_state():
472 # Reject the collision, we can walk through.
473 return False
474 return True
475
476 collide_with_furniture = collide_with_protagonist
477
478 @classmethod
479 def requires(cls):
480 return [("name", "string"), ("end1", "coordinates"),
481 ("end2", "coordinates"), ("key_state", "puzzler")]
482
483
484class ToggleSwitch(GameObject):
485 zorder = ZORDER_LOW
486
487 def __init__(self, space, position):
488 body = make_body(None, None, position)
489 self.shape = pymunk.Circle(body, 20)
490 self.shape.sensor = True
491 super(ToggleSwitch, self).__init__(
492 SingleShapePhysicser(space, self.shape),
493 render.ImageStateRenderer({
494 True: resources.get_image('objects', 'lever.png'),
495 False: resources.get_image(
496 'objects', 'lever.png', transforms=(FLIP_H,)),
497 }),
498 puzzle.ParentAttrPuzzler('toggle_on'),
499 interactible=environment.Interactible(
500 environment.Action(self._toggle)),
501 )
502
503 @property
504 def toggle_on(self):
505 return self._stored_state['toggle_on']
506
507 def _toggle(self, protagonist):
508 self._stored_state['toggle_on'] = not self.toggle_on
509
510 def set_stored_state_dict(self, stored_state):
511 self._stored_state = stored_state
512 # We start in the "off" position.
513 self._stored_state.setdefault('toggle_on', False)
514 return True
515
516 @classmethod
517 def requires(cls):
518 return [("name", "string"), ("position", "coordinates")]
519
520
521class Bullet(GameObject):
522 def __init__(self, space, position, impulse, damage, bullet_type,
523 source_collision_type):
524 body = make_body(1, pymunk.inf, position)
525 body.angle = impulse.angle
526 self.last_position = position
527 self.shape = pymunk.Circle(body, 2)
528 self.shape.sensor = True
529 self.shape.collision_type = COLLISION_TYPE_PROJECTILE
530 self.damage = damage
531 self.type = bullet_type
532 self.source_collision_type = source_collision_type
533 super(Bullet, self).__init__(
534 SingleShapePhysicser(space, self.shape),
535 render.ImageRenderer(resources.get_image(
536 'objects', '%s.png' % self.type)),
537 )
538 self.physicser.apply_impulse(impulse)
539
540 def update(self, dt):
541 super(Bullet, self).update(dt)
542 position = (self.physicser.position.x, self.physicser.position.y)
543 r = self.get_space().segment_query(self.last_position, position)
544 self.last_position = position
545 for collision in r:
546 shape = collision.shape
547 if (shape.collision_type == self.source_collision_type
548 or shape == self.physicser.get_shape()
549 or shape.sensor):
550 continue
551 if hasattr(shape, 'physicser'):
552 shape.physicser.game_object.hit(self)
553 self.physicser.remove_from_space()
554 return Result(remove=[self])
555
556
557class ClawAttack(GameObject):
558 def __init__(self, space, pos, vector, damage):
559 body = make_body(1, pymunk.inf,
560 (pos[0] + (vector.length * math.cos(vector.angle)),
561 pos[1] + (vector.length * math.sin(vector.angle))))
562 body.angle = vector.angle
563 self.shape = pymunk.Circle(body, 30)
564 self.shape.sensor = True
565 self.shape.collision_type = COLLISION_TYPE_WEREWOLF_ATTACK
566 self.damage = damage
567 super(ClawAttack, self).__init__(
568 SingleShapePhysicser(space, self.shape),
569 render.ImageRenderer(resources.get_image(
570 'objects', 'werewolf_SW_claw_attack.png',
571 transforms=(FLIP_H,))),
572 )
573
574 def update(self, dt):
575 super(ClawAttack, self).update(dt)
576 if self.lifetime > 0.1:
577 self.physicser.remove_from_space()
578 return Result(remove=[self])
579
580
581class HostileTerrain(GameObject):
582 zorder = ZORDER_FLOOR
583 damage = None
584 tiles = []
585 tile_alpha = 255
586 tile_frame_ticks = 3
587 # How often to hit the player
588 rate = 5
589
590 def __init__(self, space, position, outline):
591 body = make_body(10, pymunk.inf, position)
592 # Adjust shape relative to position
593 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
594 p in outline]
595 self.shape = pymunk.Poly(body, shape_outline)
596 self._ticks = 0
597 self.shape.collision_type = COLLISION_TYPE_SWITCH
598 self.shape.sensor = True
599 if len(self.tiles) > 1:
600 tile_images = [resources.get_image('tiles', x)
601 for x in self.tiles]
602 renderer = render.TimedTiledRenderer(outline, tile_images,
603 self.tile_frame_ticks,
604 self.tile_alpha)
605 else:
606 tile_image = resources.get_image('tiles', self.tiles[0])
607 renderer = render.TiledRenderer(outline, tile_image,
608 self.tile_alpha)
609 super(HostileTerrain, self).__init__(
610 SingleShapePhysicser(space, self.shape),
611 renderer)
612
613 def collide_with_protagonist(self, protagonist):
614 # We're called every frame we're colliding, so
615 # There are timing issues with stepping on and
616 # off terrian, but as long as the rate is reasonably
617 # low, they shouldn't impact gameplay
618 if self._ticks == 0:
619 self.apply_effect(protagonist)
620 self._ticks += 1
621 if self._ticks > self.rate:
622 self._ticks = 0
623
624 def apply_effect(self, protagonist):
625 protagonist.lose_health(self.damage)
626
627 @classmethod
628 def requires(cls):
629 return [("name", "string"), ("position", "coordinates"),
630 ("outline", "polygon (convex)")]
631
632
633class AcidFloor(HostileTerrain):
634 damage = 1
635 tiles = ['acid.png', 'acid2.png', 'acid3.png']
636 tile_alpha = 200
637 tile_frame_ticks = 10
638
639
640class ForceWolfFloor(HostileTerrain):
641 tiles = ['moonlight.png']
642 rate = 0
643 tile_alpha = 150
644 zorder = ZORDER_HIGH
645
646 def apply_effect(self, protagonist):
647 protagonist.force_wolf_form()
648
649
650class GravityWell(GameObject):
651 zorder = ZORDER_FLOOR
652 # How often to hit the player
653 rate = 5
654
655 def __init__(self, space, position, radius, force):
656 body = make_body(None, None, position)
657 # Adjust shape relative to position
658 self._radius = radius
659 self.shape = pymunk.Circle(body, radius)
660 self.centre = pymunk.Circle(body, 10)
661 self.centre.friction = pymunk.inf
662 self._ticks = 0
663 self.force = force
664 self.shape.collision_type = COLLISION_TYPE_SWITCH
665 self.shape.sensor = True
666 super(GravityWell, self).__init__(
667 MultiShapePhysicser(space, self.shape, self.centre),
668 render.ImageRenderer(resources.get_image(
669 'objects', 'gravity_well.png')),
670 )
671
672 def collide_with_protagonist(self, protagonist):
673 # We're called every frame we're colliding, so
674 # There are timing issues with stepping on and
675 # off terrian, but as long as the rate is reasonably
676 # low, they shouldn't impact gameplay
677 self.apply_effect(protagonist)
678
679 def collide_with_furniture(self, furniture):
680 # We're called every frame we're colliding, so
681 # There are timing issues with stepping on and
682 # off terrian, but as long as the rate is reasonably
683 # low, they shouldn't impact gameplay
684 self.apply_effect(furniture)
685
686 def apply_effect(self, object_to_move):
687 movement = self.physicser.position - object_to_move.physicser.position
688 local_force = self.force * (1 - (self._radius / movement.length))
689 movement.length = local_force
690 object_to_move.environmental_movement(-movement)
691
692 @classmethod
693 def requires(cls):
694 return [("name", "string"), ("position", "coordinates"),
695 ("outline", "polygon (convex)")]
696
697
698class SheepPen(GameObject):
699 zorder = ZORDER_FLOOR
700
701 def __init__(self, space, position, outline, sheep_count):
702 body = make_body(None, None, position)
703 # Adjust shape relative to position
704 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
705 p in outline]
706 self.shape = pymunk.Poly(body, shape_outline)
707 self.shape.collision_type = COLLISION_TYPE_SHEEP_PEN
708 self.shape.sensor = True
709 super(SheepPen, self).__init__(
710 SingleShapePhysicser(space, self.shape),
711 render.Renderer(),
712 puzzle.MultiCollidePuzzler(sheep_count, COLLISION_TYPE_SHEEP),
713 )
714
715 @classmethod
716 def requires(cls):
717 return [("name", "string"), ("position", "coordinates"),
718 ("outline", "polygon (convex)"), ("sheep_count", "int")]
Note: See TracBrowser for help on using the repository browser.