source: nagslang/game_object.py@ 263:6c554ce627e3

Last change on this file since 263:6c554ce627e3 was 263:6c554ce627e3, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Add angle to doors

File size: 9.7 KB
Line 
1import pymunk
2import pymunk.pygame_util
3
4import math
5
6from nagslang import puzzle
7from nagslang import render
8from nagslang.constants import (
9 SWITCH_PUSHERS, COLLISION_TYPE_SWITCH, COLLISION_TYPE_BOX, ZORDER_LOW,
10 ZORDER_FLOOR, COLLISION_TYPE_DOOR, COLLISION_TYPE_PROJECTILE)
11from nagslang.resources import resources
12from nagslang.events import DoorEvent
13
14
15def get_editable_game_objects():
16 classes = []
17 for cls_name, cls in globals().iteritems():
18 if isinstance(cls, type) and hasattr(cls, 'requires'):
19 classes.append((cls_name, cls))
20 return classes
21
22
23class Physicser(object):
24 def __init__(self, space):
25 self._space = space
26
27 def get_space(self):
28 return self._space
29
30 def set_game_object(self, game_object):
31 self.game_object = game_object
32
33 def get_shape(self):
34 raise NotImplementedError()
35
36 def add_to_space(self):
37 shape = self.get_shape()
38 self.get_space().add(shape)
39 if not shape.body.is_static:
40 self.get_space().add(shape.body)
41
42 def remove_from_space(self):
43 shape = self.get_shape()
44 self.get_space().remove(shape)
45 if not shape.body.is_static:
46 self.get_space().remove(shape.body)
47
48 def get_render_position(self, surface):
49 pos = self.get_shape().body.position
50 return pymunk.pygame_util.to_pygame(pos, surface)
51
52 def get_angle(self):
53 return self.get_shape().body.angle
54
55 def get_velocity(self):
56 return self.get_shape().body.velocity
57
58 def _get_position(self):
59 return self.get_shape().body.position
60
61 def _set_position(self, position):
62 self.get_shape().body.position = position
63
64 position = property(_get_position, _set_position)
65
66 def apply_impulse(self, j, r=(0, 0)):
67 return self.get_shape().body.apply_impulse(j, r)
68
69
70class SingleShapePhysicser(Physicser):
71 def __init__(self, space, shape):
72 super(SingleShapePhysicser, self).__init__(space)
73 self._shape = shape
74 shape.physicser = self
75
76 def get_shape(self):
77 return self._shape
78
79
80def damping_velocity_func(body, gravity, damping, dt):
81 """Apply custom damping to this body's velocity.
82 """
83 damping = getattr(body, 'damping', damping)
84 return pymunk.Body.update_velocity(body, gravity, damping, dt)
85
86
87def make_body(mass, moment, position, damping=None):
88 body = pymunk.Body(mass, moment)
89 body.position = tuple(position)
90 if damping is not None:
91 body.damping = damping
92 body.velocity_func = damping_velocity_func
93 return body
94
95
96class GameObject(object):
97 """A representation of a thing in the game world.
98
99 This has a rendery thing, physicsy things and maybe some other things.
100 """
101
102 zorder = ZORDER_LOW
103 is_moving = False # `True` if a movement animation should play.
104
105 def __init__(self, physicser, renderer, puzzler=None, overlay=None):
106 self.physicser = physicser
107 physicser.set_game_object(self)
108 self.physicser.add_to_space()
109 self.renderer = renderer
110 renderer.set_game_object(self)
111 self.puzzler = puzzler
112 if puzzler is not None:
113 puzzler.set_game_object(self)
114 self.overlay = overlay
115 if overlay is not None:
116 self.overlay.set_game_object(self)
117
118 def get_space(self):
119 return self.physicser.get_space()
120
121 def get_shape(self):
122 return self.physicser.get_shape()
123
124 def get_render_position(self, surface):
125 return self.physicser.get_render_position(surface)
126
127 def get_render_angle(self):
128 return self.physicser.get_angle()
129
130 def get_facing_direction(self):
131 """Used by rendererd that care what direction an object is facing.
132 """
133 return None
134
135 def render(self, surface):
136 return self.renderer.render(surface)
137
138 def animate(self):
139 self.renderer.animate()
140
141 def collide_with_protagonist(self, protagonist):
142 """Called as a `pre_solve` collision callback with the protagonist.
143
144 You can return `False` to ignore the collision, anything else
145 (including `None`) to process the collision as normal.
146 """
147 return True
148
149 @classmethod
150 def requires(cls):
151 """Hints for the level editor"""
152 return [("name", "string")]
153
154
155class FloorSwitch(GameObject):
156 zorder = ZORDER_FLOOR
157
158 def __init__(self, space, position):
159 body = make_body(None, None, position)
160 self.shape = pymunk.Circle(body, 30)
161 self.shape.collision_type = COLLISION_TYPE_SWITCH
162 self.shape.sensor = True
163 super(FloorSwitch, self).__init__(
164 SingleShapePhysicser(space, self.shape),
165 render.ImageStateRenderer({
166 True: resources.get_image('objects', 'sensor_on.png'),
167 False: resources.get_image('objects', 'sensor_off.png'),
168 }),
169 puzzle.CollidePuzzler(*SWITCH_PUSHERS),
170 )
171
172 @classmethod
173 def requires(cls):
174 return [("name", "string"), ("position", "coordinates")]
175
176
177class Note(GameObject):
178 zorder = ZORDER_FLOOR
179
180 def __init__(self, space, position, message):
181 body = make_body(None, None, position)
182 self.shape = pymunk.Circle(body, 30)
183 self.shape.sensor = True
184 super(Note, self).__init__(
185 SingleShapePhysicser(space, self.shape),
186 render.ImageRenderer(resources.get_image('objects', 'note.png')),
187 puzzle.CollidePuzzler(),
188 render.TextOverlay(message),
189 )
190
191 @classmethod
192 def requires(cls):
193 return [("name", "string"), ("position", "coordinates"),
194 ("message", "text")]
195
196
197class FloorLight(GameObject):
198 zorder = ZORDER_FLOOR
199
200 def __init__(self, space, position, state_source):
201 body = make_body(None, None, position)
202 self.shape = pymunk.Circle(body, 10)
203 self.shape.collision_type = COLLISION_TYPE_SWITCH
204 self.shape.sensor = True
205 super(FloorLight, self).__init__(
206 SingleShapePhysicser(space, self.shape),
207 render.ImageStateRenderer({
208 True: resources.get_image('objects', 'light_on.png'),
209 False: resources.get_image('objects', 'light_off.png'),
210 }),
211 puzzle.StateProxyPuzzler(state_source),
212 )
213
214 @classmethod
215 def requires(cls):
216 return [("name", "string"), ("position", "coordinates"),
217 ("state_source", "puzzler")]
218
219
220class Box(GameObject):
221 def __init__(self, space, position):
222 body = make_body(10, 10000, position, damping=0.5)
223 self.shape = pymunk.Poly(
224 body, [(-20, -20), (20, -20), (20, 20), (-20, 20)])
225 self.shape.friction = 0.5
226 self.shape.collision_type = COLLISION_TYPE_BOX
227 super(Box, self).__init__(
228 SingleShapePhysicser(space, self.shape),
229 render.ImageRenderer(resources.get_image('objects', 'crate.png')),
230 )
231
232 @classmethod
233 def requires(cls):
234 return [("name", "string"), ("position", "coordinates"),
235 ("state_source", "puzzler")]
236
237
238class Door(GameObject):
239 zorder = ZORDER_FLOOR
240
241 def __init__(self, space, position, destination, dest_pos, angle,
242 key_state=None):
243 body = make_body(pymunk.inf, pymunk.inf, position, damping=0.5)
244 self.shape = pymunk.Poly(
245 body, [(-4, -30), (4, -30), (4, 30), (-4, 30)])
246 self.shape.collision_type = COLLISION_TYPE_DOOR
247 self.shape.body.angle = float(angle)/180 * math.pi
248 self.shape.sensor = True
249 self.destination = destination
250 self.dest_pos = tuple(dest_pos)
251 if key_state is None:
252 puzzler = puzzle.YesPuzzler()
253 else:
254 puzzler = puzzle.StateProxyPuzzler(key_state)
255 super(Door, self).__init__(
256 SingleShapePhysicser(space, self.shape),
257 render.ImageRenderer(resources.get_image('objects', 'door.png')),
258 puzzler,
259 )
260
261 def collide_with_protagonist(self, protagonist):
262 if self.puzzler.get_state():
263 DoorEvent.post(self.destination, self.dest_pos)
264
265 @classmethod
266 def requires(cls):
267 return [("name", "string"), ("position", "coordinates"),
268 ("destination", "level name"), ("dest_pos", "coordinate"),
269 ("angle", "degrees"),
270 ("key_state", "puzzler (optional)")]
271
272
273class Bulkhead(GameObject):
274 zorder = ZORDER_FLOOR
275
276 def __init__(self, space, end1, end2, key_state=None):
277 body = make_body(None, None, (0, 0))
278 self.shape = pymunk.Segment(body, tuple(end1), tuple(end2), 3)
279 self.shape.collision_type = COLLISION_TYPE_DOOR
280 if key_state is None:
281 puzzler = puzzle.YesPuzzler()
282 else:
283 puzzler = puzzle.StateProxyPuzzler(key_state)
284 super(Bulkhead, self).__init__(
285 SingleShapePhysicser(space, self.shape),
286 render.ShapeStateRenderer(),
287 puzzler,
288 )
289
290 def collide_with_protagonist(self, protagonist):
291 if self.puzzler.get_state():
292 # Reject the collision, we can walk through.
293 return False
294 return True
295
296 @classmethod
297 def requires(cls):
298 return [("name", "string"), ("end1", "coordinates"),
299 ("end2", "coordinates"), ("key_state", "puzzler")]
300
301
302class Bullet(GameObject):
303 def __init__(self, space, position, impulse):
304 body = make_body(1, pymunk.inf, position)
305 self.shape = pymunk.Circle(body, 1)
306 self.shape.collision_type = COLLISION_TYPE_PROJECTILE
307 super(Bullet, self).__init__(
308 SingleShapePhysicser(space, self.shape),
309 render.ImageRenderer(resources.get_image('objects', 'bullet.png')),
310 )
311 self.physicser.apply_impulse(impulse)
Note: See TracBrowser for help on using the repository browser.