source: nagslang/game_object.py@ 628:db960388b912

Last change on this file since 628:db960388b912 was 628:db960388b912, checked in by Simon Cross <hodgestar@…>, 8 years ago

Blast off home.

File size: 27.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, 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, QuitEvent
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
415 image_name = "door.png"
416
417 def __init__(self, space, position, destination, dest_pos, angle):
418 super(Door, self).__init__(
419 space, position, destination, dest_pos, angle,
420 render.ImageRenderer(
421 resources.get_image('objects', self.image_name)),
422 environment.YesCondition(),
423 )
424
425 @classmethod
426 def requires(cls):
427 return [("name", "string"), ("position", "coordinates"),
428 ("destination", "level name"), ("dest_pos", "coordinate"),
429 ("angle", "degrees")]
430
431
432class RestartGameDoor(Door):
433 def _post_door_event(self, protagonist):
434 protagonist.world.reset()
435 super(RestartGameDoor, self)._post_door_event(protagonist)
436
437
438class ContinueGameDoor(Door):
439 def _post_door_event(self, protagonist):
440 world = protagonist.world
441 if world.level[0]:
442 DoorEvent.post(world.level[0], world.level[1])
443 else:
444 # New game?
445 super(ContinueGameDoor, self)._post_door_event(protagonist)
446
447
448class RocketConsole(Door):
449
450 image_name = "rocket_console.png"
451
452 def _post_door_event(self, protagonist):
453 QuitEvent.post()
454
455
456def make_overlay_image(image_name, angle):
457 transforms = ()
458 if angle != 0:
459 transforms = (rotator(-angle),)
460 return resources.get_image('objects', image_name, transforms=transforms)
461
462
463class PuzzleDoor(BaseDoor):
464 def __init__(self, space, position, destination, dest_pos, angle,
465 key_state):
466 self._key_state = key_state
467 overlay = ImageOverlay(make_overlay_image('lock.png', angle))
468 super(PuzzleDoor, self).__init__(
469 space, position, destination, dest_pos, angle,
470 render.ImageStateRenderer({
471 True: resources.get_image('objects', 'door.png'),
472 False: resources.get_image(
473 'objects', 'door.png', transforms=(overlay,)),
474 }),
475 environment.FunctionCondition(lambda p: self.is_open),
476 )
477
478 @property
479 def is_open(self):
480 if self._stored_state['is_open']:
481 return True
482 return self.puzzler.glue.get_state_of(self._key_state)
483
484 def door_opened(self):
485 self._stored_state['is_open'] = True
486 super(PuzzleDoor, self).door_opened()
487
488 def set_stored_state_dict(self, stored_state):
489 self._stored_state = stored_state
490 self._stored_state.setdefault('is_open', False)
491 return True
492
493 @classmethod
494 def requires(cls):
495 return [("name", "string"), ("position", "coordinates"),
496 ("destination", "level name"), ("dest_pos", "coordinate"),
497 ("angle", "degrees"),
498 ("key_state", "puzzler")]
499
500
501class KeyedDoor(BaseDoor):
502 def __init__(self, space, position, destination, dest_pos, angle,
503 key_item=None):
504 self._key_item = key_item
505 overlay = ImageOverlay(
506 make_overlay_image('%s.png' % (key_item,), angle))
507 super(KeyedDoor, self).__init__(
508 space, position, destination, dest_pos, angle,
509 render.ImageRenderer(resources.get_image(
510 'objects', 'door.png', transforms=(overlay,))),
511 environment.ItemRequiredCondition(key_item),
512 )
513
514 @classmethod
515 def requires(cls):
516 return [("name", "string"), ("position", "coordinates"),
517 ("destination", "level name"), ("dest_pos", "coordinate"),
518 ("angle", "degrees"), ("key_item", "item name")]
519
520
521class Hatch(GameObject):
522 zorder = ZORDER_FLOOR
523
524 def __init__(self, space, end1, end2, key_state=None):
525 a = pymunk.Vec2d(end1)
526 b = pymunk.Vec2d(end2)
527 offset = b - a
528 offset.length /= 2
529 mid = (a + offset).int_tuple
530 body = make_body(None, None, mid)
531 self.shape = pymunk.Segment(
532 body, body.world_to_local(tuple(end1)),
533 body.world_to_local(tuple(end2)), 7)
534 self.shape.collision_type = COLLISION_TYPE_DOOR
535 if key_state is None:
536 puzzler = puzzle.YesPuzzler()
537 else:
538 puzzler = puzzle.StateProxyPuzzler(key_state)
539 super(Hatch, self).__init__(
540 SingleShapePhysicser(space, self.shape),
541 render.HatchRenderer(),
542 puzzler,
543 )
544
545 def collide_with_protagonist(self, protagonist):
546 if self.puzzler.get_state():
547 # Reject the collision, we can walk through.
548 return False
549 return True
550
551 collide_with_furniture = collide_with_protagonist
552
553 @classmethod
554 def requires(cls):
555 return [("name", "string"), ("end1", "coordinates"),
556 ("end2", "coordinates"), ("key_state", "puzzler")]
557
558 # The level knows that hatches are magical
559 @classmethod
560 def movable(cls):
561 return True
562
563
564class KeyedHatch(GameObject):
565 zorder = ZORDER_FLOOR
566
567 def __init__(self, space, end1, end2, key_item):
568 a = pymunk.Vec2d(end1)
569 b = pymunk.Vec2d(end2)
570 offset = b - a
571 offset.length /= 2
572 mid = (a + offset).int_tuple
573 body = make_body(None, None, mid)
574 self.shape = pymunk.Segment(
575 body, body.world_to_local(tuple(end1)),
576 body.world_to_local(tuple(end2)), 7)
577 self.shape.collision_type = COLLISION_TYPE_DOOR
578 other_shape = pymunk.Circle(body, 30)
579 other_shape.collision_type = COLLISION_TYPE_DOOR
580 other_shape.sensor = True
581 self._key_item = key_item
582 super(KeyedHatch, self).__init__(
583 MultiShapePhysicser(space, self.shape, other_shape),
584 render.KeyedHatchRenderer(
585 resources.get_image(
586 'objects', '%s.png' % (key_item,),
587 transforms=(scaler((32, 32)),))),
588 puzzle.ParentAttrPuzzler('is_open'),
589 )
590 self.add_timer('door_open', 0.1)
591
592 @property
593 def is_open(self):
594 return self.check_timer('door_open')
595
596 def collide_with_protagonist(self, protagonist):
597 if protagonist.has_item(self._key_item):
598 self.start_timer('door_open')
599 return False
600 return True
601
602 @classmethod
603 def requires(cls):
604 return [("name", "string"), ("end1", "coordinates"),
605 ("end2", "coordinates"), ("key_item", "item name")]
606
607 # The level knows that hatches are magical
608 @classmethod
609 def movable(cls):
610 return True
611
612
613class ToggleSwitch(GameObject):
614 zorder = ZORDER_LOW
615
616 def __init__(self, space, position):
617 body = make_body(None, None, position)
618 self.shape = pymunk.Circle(body, 20)
619 self.shape.sensor = True
620 super(ToggleSwitch, self).__init__(
621 SingleShapePhysicser(space, self.shape),
622 render.ImageStateRenderer({
623 True: resources.get_image('objects', 'lever.png'),
624 False: resources.get_image(
625 'objects', 'lever.png', transforms=(FLIP_H,)),
626 }),
627 puzzle.ParentAttrPuzzler('toggle_on'),
628 interactible=environment.Interactible(
629 environment.Action(self._toggle)),
630 )
631
632 @property
633 def toggle_on(self):
634 return self._stored_state['toggle_on']
635
636 def _toggle(self, protagonist):
637 self._stored_state['toggle_on'] = not self.toggle_on
638
639 def set_stored_state_dict(self, stored_state):
640 self._stored_state = stored_state
641 # We start in the "off" position.
642 self._stored_state.setdefault('toggle_on', False)
643 return True
644
645 @classmethod
646 def requires(cls):
647 return [("name", "string"), ("position", "coordinates")]
648
649
650class Bullet(GameObject):
651 def __init__(self, space, position, impulse, damage, bullet_type,
652 source_collision_type, bullet_sound=None):
653 body = make_body(1, pymunk.inf, position)
654 body.angle = impulse.angle
655 self.last_position = position
656 self.shape = pymunk.Circle(body, 2)
657 self.shape.sensor = True
658 self.shape.collision_type = COLLISION_TYPE_PROJECTILE
659 self.damage = damage
660 self.type = bullet_type
661 self.source_collision_type = source_collision_type
662 super(Bullet, self).__init__(
663 SingleShapePhysicser(space, self.shape),
664 render.ImageRenderer(resources.get_image(
665 'objects', '%s.png' % self.type)),
666 )
667 self.physicser.apply_impulse(impulse)
668 if bullet_sound is not None:
669 sound.play_sound(bullet_sound, 0.3)
670
671 def update(self, dt):
672 super(Bullet, self).update(dt)
673 position = (self.physicser.position.x, self.physicser.position.y)
674 r = self.get_space().segment_query(self.last_position, position)
675 self.last_position = position
676 for collision in r:
677 shape = collision.shape
678 if (shape.collision_type == self.source_collision_type
679 or shape == self.physicser.get_shape()
680 or shape.sensor):
681 continue
682 if hasattr(shape, 'physicser'):
683 shape.physicser.game_object.hit(self)
684 self.physicser.remove_from_space()
685 return Result(remove=[self])
686
687
688class ClawAttack(GameObject):
689 def __init__(self, space, pos, vector, damage):
690 body = make_body(1, pymunk.inf,
691 (pos[0] + (vector.length * math.cos(vector.angle)),
692 pos[1] + (vector.length * math.sin(vector.angle))))
693 body.angle = vector.angle
694 self.shape = pymunk.Circle(body, 30)
695 self.shape.sensor = True
696 self.shape.collision_type = COLLISION_TYPE_WEREWOLF_ATTACK
697 self.damage = damage
698 super(ClawAttack, self).__init__(
699 SingleShapePhysicser(space, self.shape),
700 render.ImageRenderer(resources.get_image(
701 'objects', 'werewolf_SW_claw_attack.png',
702 transforms=(FLIP_H,))),
703 )
704
705 def update(self, dt):
706 super(ClawAttack, self).update(dt)
707 if self.lifetime > 0.1:
708 self.physicser.remove_from_space()
709 return Result(remove=[self])
710
711
712class HostileTerrain(GameObject):
713 zorder = ZORDER_FLOOR
714 damage = None
715 tiles = []
716 tile_alpha = 255
717 tile_frame_ticks = 3
718 # How often to hit the player
719 rate = 5
720
721 def __init__(self, space, position, outline):
722 body = make_body(10, pymunk.inf, position)
723 # Adjust shape relative to position
724 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
725 p in outline]
726 self.shape = pymunk.Poly(body, shape_outline)
727 self._ticks = 0
728 self.shape.collision_type = COLLISION_TYPE_SWITCH
729 self.shape.sensor = True
730 renderer = self._fix_image(outline)
731 self._collider = puzzle.CollidePuzzler()
732 self._collider.set_game_object(self)
733 self._protagonist = None
734 super(HostileTerrain, self).__init__(
735 SingleShapePhysicser(space, self.shape),
736 renderer)
737
738 def _fix_image(self, outline):
739 if len(self.tiles) > 1:
740 tile_images = [resources.get_image('tiles', x)
741 for x in self.tiles]
742 renderer = render.TimedTiledRenderer(outline, tile_images,
743 self.tile_frame_ticks,
744 self.tile_alpha)
745 else:
746 tile_image = resources.get_image('tiles', self.tiles[0])
747 renderer = render.TiledRenderer(outline, tile_image,
748 self.tile_alpha)
749 return renderer
750
751 def update_image(self, new_outline):
752 self.renderer = self._fix_image(new_outline)
753
754 def update(self, seconds):
755 if self._collider.get_state():
756 if self._ticks == 0:
757 self.apply_effect(self._protagonist)
758 self._ticks += 1
759 if self._ticks > self.rate:
760 self._ticks = 0
761
762 def collide_with_protagonist(self, protagonist):
763 self._protagonist = protagonist
764
765 def apply_effect(self, protagonist):
766 protagonist.lose_health(self.damage)
767
768 @classmethod
769 def requires(cls):
770 return [("name", "string"), ("position", "coordinates"),
771 ("outline", "polygon (convex)")]
772
773
774class AcidFloor(HostileTerrain):
775 damage = 1
776 tiles = ['acid.png', 'acid2.png', 'acid3.png']
777 tile_alpha = 200
778 tile_frame_ticks = 10
779
780
781class ForceWolfFloor(HostileTerrain):
782 tiles = ['moonlight.png']
783 rate = 0
784 tile_alpha = 150
785 zorder = ZORDER_HIGH
786
787 def apply_effect(self, protagonist):
788 protagonist.force_wolf_form()
789
790
791class GravityWell(GameObject):
792 zorder = ZORDER_FLOOR
793 # How often to hit the player
794 rate = 5
795
796 def __init__(self, space, position, radius, force):
797 body = make_body(None, None, position)
798 # Adjust shape relative to position
799 self._radius = radius
800 self.shape = pymunk.Circle(body, radius)
801 self.centre = pymunk.Circle(body, 10)
802 self.centre.friction = pymunk.inf
803 self._ticks = 0
804 self.force = force
805 self.shape.collision_type = COLLISION_TYPE_SWITCH
806 self.shape.sensor = True
807 super(GravityWell, self).__init__(
808 MultiShapePhysicser(space, self.shape, self.centre),
809 render.ImageRenderer(resources.get_image(
810 'objects', 'gravity_well.png')),
811 )
812
813 def collide_with_protagonist(self, protagonist):
814 # We're called every frame we're colliding, so
815 # There are timing issues with stepping on and
816 # off terrian, but as long as the rate is reasonably
817 # low, they shouldn't impact gameplay
818 self.apply_effect(protagonist)
819
820 def collide_with_furniture(self, furniture):
821 # We're called every frame we're colliding, so
822 # There are timing issues with stepping on and
823 # off terrian, but as long as the rate is reasonably
824 # low, they shouldn't impact gameplay
825 self.apply_effect(furniture)
826
827 def apply_effect(self, object_to_move):
828 movement = self.physicser.position - object_to_move.physicser.position
829 local_force = self.force * math.sqrt(
830 object_to_move.get_shape().body.mass)
831 movement.length = local_force
832 object_to_move.environmental_movement(movement)
833
834 @classmethod
835 def requires(cls):
836 return [("name", "string"), ("position", "coordinates"),
837 ("radius", "int"), ("force", "int")]
838
839
840class SheepPen(GameObject):
841 zorder = ZORDER_FLOOR
842
843 def __init__(self, space, position, outline, sheep_count):
844 body = make_body(None, None, position)
845 # Adjust shape relative to position
846 shape_outline = [(p[0] - position[0], p[1] - position[1]) for
847 p in outline]
848 self.shape = pymunk.Poly(body, shape_outline)
849 self.shape.collision_type = COLLISION_TYPE_SHEEP_PEN
850 self.shape.sensor = True
851 super(SheepPen, self).__init__(
852 SingleShapePhysicser(space, self.shape),
853 render.Renderer(),
854 puzzle.MultiCollidePuzzler(sheep_count, COLLISION_TYPE_SHEEP),
855 )
856
857 @classmethod
858 def requires(cls):
859 return [("name", "string"), ("position", "coordinates"),
860 ("outline", "polygon (convex)"), ("sheep_count", "int")]
Note: See TracBrowser for help on using the repository browser.