source: nagslang/game_object.py@ 510:2cdfbc483d57

Last change on this file since 510:2cdfbc483d57 was 510:2cdfbc483d57, checked in by Stefano Rivera <stefano@…>, 8 years ago

Don't put the starting level in the world, it just creates too much pain

File size: 23.6 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 if world.level[0]:
393 DoorEvent.post(world.level[0], world.level[1])
394 else:
395 # New game?
396 super(ContinueGameDoor, self)._post_door_event(protagonist)
397
398
399class PuzzleDoor(BaseDoor):
400 def __init__(self, space, position, destination, dest_pos, angle,
401 key_state):
402 self._key_state = key_state
403 overlay = ImageOverlay(resources.get_image('objects', 'lock.png'))
404 super(PuzzleDoor, self).__init__(
405 space, position, destination, dest_pos, angle,
406 render.ImageStateRenderer({
407 True: resources.get_image('objects', 'door.png'),
408 False: resources.get_image(
409 'objects', 'door.png', transforms=(overlay,)),
410 }),
411 environment.FunctionCondition(lambda p: self.is_open),
412 )
413
414 @property
415 def is_open(self):
416 return self._stored_state['is_open']
417
418 def set_stored_state_dict(self, stored_state):
419 self._stored_state = stored_state
420 self._stored_state.setdefault('is_open', False)
421 return True
422
423 def update(self, dt):
424 if not self.is_open:
425 self._stored_state['is_open'] = self.puzzler.glue.get_state_of(
426 self._key_state)
427 super(PuzzleDoor, self).update(dt)
428
429 @classmethod
430 def requires(cls):
431 return [("name", "string"), ("position", "coordinates"),
432 ("destination", "level name"), ("dest_pos", "coordinate"),
433 ("angle", "degrees"),
434 ("key_state", "puzzler")]
435
436
437class KeyedDoor(BaseDoor):
438 def __init__(self, space, position, destination, dest_pos, angle,
439 key_item=None):
440 self._key_item = key_item
441 overlay = ImageOverlay(
442 resources.get_image('objects', '%s.png' % (key_item,)))
443 super(KeyedDoor, self).__init__(
444 space, position, destination, dest_pos, angle,
445 render.ImageRenderer(resources.get_image(
446 'objects', 'door.png', transforms=(overlay,))),
447 environment.ItemRequiredCondition(key_item),
448 )
449
450 @classmethod
451 def requires(cls):
452 return [("name", "string"), ("position", "coordinates"),
453 ("destination", "level name"), ("dest_pos", "coordinate"),
454 ("angle", "degrees"), ("key_item", "item name")]
455
456
457class Bulkhead(GameObject):
458 zorder = ZORDER_FLOOR
459
460 def __init__(self, space, end1, end2, key_state=None):
461 body = make_body(None, None, (0, 0))
462 self.shape = pymunk.Segment(body, tuple(end1), tuple(end2), 7)
463 self.shape.collision_type = COLLISION_TYPE_DOOR
464 if key_state is None:
465 puzzler = puzzle.YesPuzzler()
466 else:
467 puzzler = puzzle.StateProxyPuzzler(key_state)
468 super(Bulkhead, self).__init__(
469 SingleShapePhysicser(space, self.shape),
470 render.BulkheadRenderer(),
471 puzzler,
472 )
473
474 def collide_with_protagonist(self, protagonist):
475 if self.puzzler.get_state():
476 # Reject the collision, we can walk through.
477 return False
478 return True
479
480 collide_with_furniture = collide_with_protagonist
481
482 @classmethod
483 def requires(cls):
484 return [("name", "string"), ("end1", "coordinates"),
485 ("end2", "coordinates"), ("key_state", "puzzler")]
486
487
488class ToggleSwitch(GameObject):
489 zorder = ZORDER_LOW
490
491 def __init__(self, space, position):
492 body = make_body(None, None, position)
493 self.shape = pymunk.Circle(body, 20)
494 self.shape.sensor = True
495 super(ToggleSwitch, self).__init__(
496 SingleShapePhysicser(space, self.shape),
497 render.ImageStateRenderer({
498 True: resources.get_image('objects', 'lever.png'),
499 False: resources.get_image(
500 'objects', 'lever.png', transforms=(FLIP_H,)),
501 }),
502 puzzle.ParentAttrPuzzler('toggle_on'),
503 interactible=environment.Interactible(
504 environment.Action(self._toggle)),
505 )
506
507 @property
508 def toggle_on(self):
509 return self._stored_state['toggle_on']
510
511 def _toggle(self, protagonist):
512 self._stored_state['toggle_on'] = not self.toggle_on
513
514 def set_stored_state_dict(self, stored_state):
515 self._stored_state = stored_state
516 # We start in the "off" position.
517 self._stored_state.setdefault('toggle_on', False)
518 return True
519
520 @classmethod
521 def requires(cls):
522 return [("name", "string"), ("position", "coordinates")]
523
524
525class Bullet(GameObject):
526 def __init__(self, space, position, impulse, damage, bullet_type,
527 source_collision_type):
528 body = make_body(1, pymunk.inf, position)
529 body.angle = impulse.angle
530 self.last_position = position
531 self.shape = pymunk.Circle(body, 2)
532 self.shape.sensor = True
533 self.shape.collision_type = COLLISION_TYPE_PROJECTILE
534 self.damage = damage
535 self.type = bullet_type
536 self.source_collision_type = source_collision_type
537 super(Bullet, self).__init__(
538 SingleShapePhysicser(space, self.shape),
539 render.ImageRenderer(resources.get_image(
540 'objects', '%s.png' % self.type)),
541 )
542 self.physicser.apply_impulse(impulse)
543
544 def update(self, dt):
545 super(Bullet, self).update(dt)
546 position = (self.physicser.position.x, self.physicser.position.y)
547 r = self.get_space().segment_query(self.last_position, position)
548 self.last_position = position
549 for collision in r:
550 shape = collision.shape
551 if (shape.collision_type == self.source_collision_type
552 or shape == self.physicser.get_shape()
553 or shape.sensor):
554 continue
555 if hasattr(shape, 'physicser'):
556 shape.physicser.game_object.hit(self)
557 self.physicser.remove_from_space()
558 return Result(remove=[self])
559
560
561class ClawAttack(GameObject):
562 def __init__(self, space, pos, vector, damage):
563 body = make_body(1, pymunk.inf,
564 (pos[0] + (vector.length * math.cos(vector.angle)),
565 pos[1] + (vector.length * math.sin(vector.angle))))
566 body.angle = vector.angle
567 self.shape = pymunk.Circle(body, 30)
568 self.shape.sensor = True
569 self.shape.collision_type = COLLISION_TYPE_WEREWOLF_ATTACK
570 self.damage = damage
571 super(ClawAttack, self).__init__(
572 SingleShapePhysicser(space, self.shape),
573 render.ImageRenderer(resources.get_image(
574 'objects', 'werewolf_SW_claw_attack.png',
575 transforms=(FLIP_H,))),
576 )
577
578 def update(self, dt):
579 super(ClawAttack, self).update(dt)
580 if self.lifetime > 0.1:
581 self.physicser.remove_from_space()
582 return Result(remove=[self])
583
584
585class HostileTerrain(GameObject):
586 zorder = ZORDER_FLOOR
587 damage = None
588 tiles = []
589 tile_alpha = 255
590 tile_frame_ticks = 3
591 # How often to hit the player
592 rate = 5
593
594 def __init__(self, space, position, outline):
595 body = make_body(10, pymunk.inf, position)
596 # Adjust shape relative to position
597 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
598 p in outline]
599 self.shape = pymunk.Poly(body, shape_outline)
600 self._ticks = 0
601 self.shape.collision_type = COLLISION_TYPE_SWITCH
602 self.shape.sensor = True
603 if len(self.tiles) > 1:
604 tile_images = [resources.get_image('tiles', x)
605 for x in self.tiles]
606 renderer = render.TimedTiledRenderer(outline, tile_images,
607 self.tile_frame_ticks,
608 self.tile_alpha)
609 else:
610 tile_image = resources.get_image('tiles', self.tiles[0])
611 renderer = render.TiledRenderer(outline, tile_image,
612 self.tile_alpha)
613 super(HostileTerrain, self).__init__(
614 SingleShapePhysicser(space, self.shape),
615 renderer)
616
617 def collide_with_protagonist(self, protagonist):
618 # We're called every frame we're colliding, so
619 # There are timing issues with stepping on and
620 # off terrian, but as long as the rate is reasonably
621 # low, they shouldn't impact gameplay
622 if self._ticks == 0:
623 self.apply_effect(protagonist)
624 self._ticks += 1
625 if self._ticks > self.rate:
626 self._ticks = 0
627
628 def apply_effect(self, protagonist):
629 protagonist.lose_health(self.damage)
630
631 @classmethod
632 def requires(cls):
633 return [("name", "string"), ("position", "coordinates"),
634 ("outline", "polygon (convex)")]
635
636
637class AcidFloor(HostileTerrain):
638 damage = 1
639 tiles = ['acid.png', 'acid2.png', 'acid3.png']
640 tile_alpha = 200
641 tile_frame_ticks = 10
642
643
644class ForceWolfFloor(HostileTerrain):
645 tiles = ['moonlight.png']
646 rate = 0
647 tile_alpha = 150
648 zorder = ZORDER_HIGH
649
650 def apply_effect(self, protagonist):
651 protagonist.force_wolf_form()
652
653
654class GravityWell(GameObject):
655 zorder = ZORDER_FLOOR
656 # How often to hit the player
657 rate = 5
658
659 def __init__(self, space, position, radius, force):
660 body = make_body(None, None, position)
661 # Adjust shape relative to position
662 self._radius = radius
663 self.shape = pymunk.Circle(body, radius)
664 self.centre = pymunk.Circle(body, 10)
665 self.centre.friction = pymunk.inf
666 self._ticks = 0
667 self.force = force
668 self.shape.collision_type = COLLISION_TYPE_SWITCH
669 self.shape.sensor = True
670 super(GravityWell, self).__init__(
671 MultiShapePhysicser(space, self.shape, self.centre),
672 render.ImageRenderer(resources.get_image(
673 'objects', 'gravity_well.png')),
674 )
675
676 def collide_with_protagonist(self, protagonist):
677 # We're called every frame we're colliding, so
678 # There are timing issues with stepping on and
679 # off terrian, but as long as the rate is reasonably
680 # low, they shouldn't impact gameplay
681 self.apply_effect(protagonist)
682
683 def collide_with_furniture(self, furniture):
684 # We're called every frame we're colliding, so
685 # There are timing issues with stepping on and
686 # off terrian, but as long as the rate is reasonably
687 # low, they shouldn't impact gameplay
688 self.apply_effect(furniture)
689
690 def apply_effect(self, object_to_move):
691 movement = self.physicser.position - object_to_move.physicser.position
692 local_force = self.force * (1 - (self._radius / movement.length))
693 movement.length = local_force
694 object_to_move.environmental_movement(-movement)
695
696 @classmethod
697 def requires(cls):
698 return [("name", "string"), ("position", "coordinates"),
699 ("outline", "polygon (convex)")]
700
701
702class SheepPen(GameObject):
703 zorder = ZORDER_FLOOR
704
705 def __init__(self, space, position, outline, sheep_count):
706 body = make_body(None, None, position)
707 # Adjust shape relative to position
708 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
709 p in outline]
710 self.shape = pymunk.Poly(body, shape_outline)
711 self.shape.collision_type = COLLISION_TYPE_SHEEP_PEN
712 self.shape.sensor = True
713 super(SheepPen, self).__init__(
714 SingleShapePhysicser(space, self.shape),
715 render.Renderer(),
716 puzzle.MultiCollidePuzzler(sheep_count, COLLISION_TYPE_SHEEP),
717 )
718
719 @classmethod
720 def requires(cls):
721 return [("name", "string"), ("position", "coordinates"),
722 ("outline", "polygon (convex)"), ("sheep_count", "int")]
Note: See TracBrowser for help on using the repository browser.