source: nagslang/screens/area.py@ 482:1b7accf22999

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

Set clip rect on mysurface.

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