source: nagslang/game_object.py@ 614:baff8131cd73

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

Heavier SokoBoxes are sturdier.

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