source: nagslang/screens/area.py@ 471:616f08c0f096

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

None is the same as not changing screen (it's dry but you can commit it).

File size: 9.8 KB
RevLine 
[18]1"""Display a game area."""
2
[20]3import pygame
[21]4import pymunk
5import pymunk.pygame_util
[20]6
[301]7from nagslang.constants import (
[319]8 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
[336]9 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
[371]10 CMD_TOGGLE_FORM, CMD_ACTION)
[440]11from nagslang.events import ScreenChange, DoorEvent, QuitEvent, DeathEvent
[50]12from nagslang.level import Level
[65]13from nagslang.screens.base import Screen
[269]14from nagslang.sound import sound
[18]15
[83]16
[34]17class ControlKeys(object):
[100]18 direction_keys = {
19 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
20 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
21 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
22 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
23 }
24
[371]25 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
26
[336]27 command_keys = {
28 pygame.locals.K_c: CMD_TOGGLE_FORM,
29 pygame.locals.K_SPACE: CMD_ACTION,
30 }
31
[34]32 def __init__(self):
33 self.keys_down = set()
34
35 def key_down(self, key):
36 self.keys_down.add(key)
37
38 def key_up(self, key):
39 self.keys_down.discard(key)
40
41 def handle_event(self, ev):
42 if ev.type == pygame.locals.KEYDOWN:
43 self.key_down(ev.key)
44 elif ev.type == pygame.locals.KEYUP:
45 self.key_up(ev.key)
46
[100]47 def get_direction(self):
48 dx, dy = 0, 0
49 for (tx, ty), keys in self.direction_keys.iteritems():
50 if self.keys_down & keys:
51 dx += tx
52 dy += ty
53 return (dx, dy)
54
[371]55 def is_attacking(self):
56 return bool(self.keys_down & self.attack_keys)
57
[336]58 def get_command_key(self, key):
59 return self.command_keys.get(key, None)
60
[34]61
[107]62class Drawables(object):
63 def __init__(self):
64 self._drawables = {}
65
66 def add(self, drawable):
67 self._drawables.setdefault(drawable.zorder, []).append(drawable)
68
69 def remove(self, drawable):
70 self._drawables[drawable.zorder].remove(drawable)
71
72 def get_drawables(self):
73 for zorder in sorted(self._drawables):
74 for drawable in self._drawables[zorder]:
75 yield drawable
76
77 __iter__ = get_drawables
78
79
[18]80class AreaScreen(Screen):
[21]81
[37]82 def setup(self):
[190]83 self._disable_render = False # Avoid redrawing on scene changes
[34]84 self.keys = ControlKeys()
[277]85 self._level = Level(self.name, self.world)
[145]86 self._level.load(self.space)
[437]87 self.game_starting_point = Level.game_starting_point()
[107]88 self._drawables = Drawables()
[37]89 self.add_walls()
[188]90 self._add_collision_handlers()
[276]91 self.add_protagonist()
[145]92 self.add_game_objects()
[269]93 sound.play_music("POL-cyber-factory-short.ogg")
[21]94
[272]95 def teardown(self):
96 sound.stop()
97
[321]98 @classmethod
99 def list_areas(self):
100 return Level.list_levels()
101
[319]102 def _player_collision_pre_solve_handler(self, space, arbiter):
[188]103 gobj = arbiter.shapes[1].physicser.game_object
[256]104 result = gobj.collide_with_protagonist(self.protagonist)
[192]105 # The collision handler must return `True` or `False`. We don't want to
106 # accidentally reject collisions from handlers that return `None`, so
107 # we explicitly check for `False` and treate everything else as `True`.
[333]108 return result is not False
109
110 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
111 claw = arbiter.shapes[0].physicser.game_object
112 gobj = arbiter.shapes[1].physicser.game_object
113 result = gobj.collide_with_claw_attack(claw)
114 return result is not False
[188]115
[319]116 def _furniture_collision_pre_solve_handler(self, space, arbiter):
117 furniture = arbiter.shapes[0].physicser.game_object
118 gobj = arbiter.shapes[1].physicser.game_object
119 result = gobj.collide_with_furniture(furniture)
120 return result is not False
121
[188]122 def _add_collision_handlers(self):
123 for collision_type in CALLBACK_COLLIDERS:
124 self.space.add_collision_handler(
125 COLLISION_TYPE_PLAYER, collision_type,
[319]126 pre_solve=self._player_collision_pre_solve_handler)
127 self.space.add_collision_handler(
128 COLLISION_TYPE_FURNITURE, collision_type,
129 pre_solve=self._furniture_collision_pre_solve_handler)
[333]130 self.space.add_collision_handler(
131 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
132 pre_solve=self._claw_attack_collision_pre_solve_handler)
[188]133
[37]134 def add_walls(self):
[21]135 self.walls = []
136 body = pymunk.Body()
[84]137 body.position = (0, 0)
[53]138 walls = self._level.get_walls()
139 for wall in walls:
[279]140 if len(wall) < 2:
141 # Don't try to add a useless wall
142 continue
[53]143 corners = wall
144 corner = corners[-1]
145 for next_corner in corners:
146 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]147 wall.collision_type = COLLISION_TYPE_WALL
[53]148 wall.elasticity = 1.0
149 self.walls.append(wall)
150 corner = next_corner
[21]151 self.space.add(*self.walls)
152
[145]153 def add_game_objects(self):
[191]154 for drawable in self._level.drawables:
[145]155 self._drawables.add(drawable)
156
[37]157 def add_protagonist(self):
[276]158 self.protagonist = self.world.protagonist
159 self.protagonist.change_space(self.space)
[107]160 self._drawables.add(self.protagonist)
[21]161
[18]162 def handle_event(self, ev):
[20]163 if ev.type == pygame.locals.KEYDOWN:
164 if ev.key == pygame.locals.K_ESCAPE:
[469]165 print self.protagonist.physicser.position
[437]166 if self._level.is_starting_level():
167 QuitEvent.post()
168 return
[440]169 self.protagonist.die()
[437]170 return
[336]171 cmd_key = self.keys.get_command_key(ev.key)
172 if cmd_key is not None:
173 self.protagonist.handle_keypress(cmd_key)
[180]174 elif DoorEvent.matches(ev):
175 self.protagonist.set_position(ev.dest_pos)
[471]176 if ev.destination is not None and ev.destination != self.name:
[180]177 # Go to anther screen
[190]178 self._disable_render = True
[238]179 self.world.rooms += 1
[345]180 self.world.level = (ev.destination, ev.dest_pos)
[399]181 self.world.save()
[276]182 ScreenChange.post(ev.destination)
[190]183 return
[180]184 # else we're teleporting within the screen, and just the
185 # position change is enough
[440]186 elif DeathEvent.matches(ev):
187 self._disable_render = True
188 self.world.load()
189 self.world.deaths += 1
190 level, pos = Level.game_starting_point()
191 self.protagonist.set_position(pos)
192 ScreenChange.post(level)
193
[34]194 self.keys.handle_event(ev)
[18]195
[87]196 def _calc_viewport(self, level_surface, display_surface):
197 level_size = level_surface.get_size()
198 display_size = display_surface.get_size()
[93]199 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]200 level_surface)
[87]201 x_wide = display_size[0] // 2
202 y_wide = display_size[1] // 2
[127]203 if display_size[0] > level_size[0]:
204 x = -(display_size[0] - level_size[0]) // 2
205 elif protagnist_pos[0] < x_wide:
[87]206 x = 0
207 elif protagnist_pos[0] > level_size[0] - x_wide:
208 x = level_size[0] - display_size[0]
209 else:
210 x = protagnist_pos[0] - x_wide
[127]211 if display_size[1] > level_size[1]:
212 y = -(display_size[1] - level_size[1]) // 2
213 elif protagnist_pos[1] < y_wide:
[87]214 y = 0
215 elif protagnist_pos[1] > level_size[1] - y_wide:
216 y = level_size[1] - display_size[1]
217 else:
218 y = protagnist_pos[1] - y_wide
219 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
220
[18]221 def render(self, surface):
[190]222 if self._disable_render:
223 return
[50]224 background = self._level.get_background()
[84]225 mysurface = background.copy()
[105]226 for drawable in self._drawables:
227 drawable.render(mysurface)
[87]228 render_rect = self._calc_viewport(mysurface, surface)
229 surface.blit(mysurface, (0, 0), render_rect)
[396]230 # Maximum width we allow for overlays
231 max_width = min(render_rect.width, mysurface.get_width())
[191]232 for overlay in self._level.overlay_drawables:
233 if overlay.is_visible():
[396]234 overlay.render(surface, render_rect.topleft, max_width)
[243]235 self.render_health_bar(surface)
[34]236
237 def tick_protagonist(self):
[100]238 dx, dy = self.keys.get_direction()
[47]239 self.protagonist.set_direction(dx, dy)
[371]240 if self.keys.is_attacking():
[393]241 self._handle_result(self.protagonist.handle_attack_key_down())
[34]242
243 def tick(self, seconds):
[303]244 super(AreaScreen, self).tick(seconds)
[34]245 self.tick_protagonist()
[143]246 for drawable in self._drawables:
[393]247 self._handle_result(drawable.update(seconds))
248
249 def _handle_result(self, result):
250 if result is not None:
251 for drawable in result.add:
252 self._drawables.add(drawable)
253 for drawable in result.remove:
254 self._drawables.remove(drawable)
[243]255
[258]256 def render_health_bar(self, surface, damage_experienced=None):
[347]257 bar_surface = pygame.Surface((110, 50)).convert(surface)
[258]258 if damage_experienced:
259 health_box_colour = pygame.color.THECOLORS['red']
260 else:
261 health_box_colour = pygame.color.THECOLORS['white']
[347]262 bar_surface.fill(health_box_colour)
[246]263 if self.protagonist.in_human_form():
[243]264 health_colour = pygame.color.THECOLORS['red']
265 else:
[340]266 health_colour = pygame.color.THECOLORS['violetred3']
[347]267 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 40)
268 pygame.draw.rect(bar_surface, health_colour, rect, 0)
269 bar_surface.set_alpha(192)
[365]270 y_pos = surface.get_height() - 20 - bar_surface.get_height()
271 surface.blit(bar_surface, (20, y_pos))
Note: See TracBrowser for help on using the repository browser.