source: nagslang/screens/area.py@ 313:768e1d06155f

Last change on this file since 313:768e1d06155f was 313:768e1d06155f, checked in by David Sharpe, 8 years ago

PEP8

File size: 8.2 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 (
8 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS)
[308]9from nagslang.enemies import DeadEnemy
[313]10from nagslang.events import ScreenChange, DoorEvent, FireEvent, \
11 EnemyDeathEvent, ClawEvent
[50]12from nagslang.level import Level
[65]13from nagslang.screens.base import Screen
[312]14from nagslang.game_object import Bullet, ClawAttack
[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
[34]26 def __init__(self):
27 self.keys_down = set()
28
29 def key_down(self, key):
30 self.keys_down.add(key)
31
32 def key_up(self, key):
33 self.keys_down.discard(key)
34
35 def handle_event(self, ev):
36 if ev.type == pygame.locals.KEYDOWN:
37 self.key_down(ev.key)
38 elif ev.type == pygame.locals.KEYUP:
39 self.key_up(ev.key)
40
[100]41 def get_direction(self):
42 dx, dy = 0, 0
43 for (tx, ty), keys in self.direction_keys.iteritems():
44 if self.keys_down & keys:
45 dx += tx
46 dy += ty
47 return (dx, dy)
48
[34]49
[107]50class Drawables(object):
51 def __init__(self):
52 self._drawables = {}
53
54 def add(self, drawable):
55 self._drawables.setdefault(drawable.zorder, []).append(drawable)
56
57 def remove(self, drawable):
58 self._drawables[drawable.zorder].remove(drawable)
59
60 def get_drawables(self):
61 for zorder in sorted(self._drawables):
62 for drawable in self._drawables[zorder]:
63 yield drawable
64
65 __iter__ = get_drawables
66
67
[18]68class AreaScreen(Screen):
[21]69
[37]70 def setup(self):
[190]71 self._disable_render = False # Avoid redrawing on scene changes
[34]72 self.keys = ControlKeys()
[277]73 self._level = Level(self.name, self.world)
[145]74 self._level.load(self.space)
[107]75 self._drawables = Drawables()
[37]76 self.add_walls()
[188]77 self._add_collision_handlers()
[276]78 self.add_protagonist()
[145]79 self.add_game_objects()
[269]80 sound.play_music("POL-cyber-factory-short.ogg")
[21]81
[272]82 def teardown(self):
83 sound.stop()
84
[188]85 def _collision_pre_solve_handler(self, space, arbiter):
86 gobj = arbiter.shapes[1].physicser.game_object
[256]87 result = gobj.collide_with_protagonist(self.protagonist)
[192]88 # The collision handler must return `True` or `False`. We don't want to
89 # accidentally reject collisions from handlers that return `None`, so
90 # we explicitly check for `False` and treate everything else as `True`.
[188]91 if result is False:
92 return False
93 return True
94
95 def _add_collision_handlers(self):
96 for collision_type in CALLBACK_COLLIDERS:
97 self.space.add_collision_handler(
98 COLLISION_TYPE_PLAYER, collision_type,
99 pre_solve=self._collision_pre_solve_handler)
100
[37]101 def add_walls(self):
[21]102 self.walls = []
103 body = pymunk.Body()
[84]104 body.position = (0, 0)
[53]105 walls = self._level.get_walls()
106 for wall in walls:
[279]107 if len(wall) < 2:
108 # Don't try to add a useless wall
109 continue
[53]110 corners = wall
111 corner = corners[-1]
112 for next_corner in corners:
113 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]114 wall.collision_type = COLLISION_TYPE_WALL
[53]115 wall.elasticity = 1.0
116 self.walls.append(wall)
117 corner = next_corner
[21]118 self.space.add(*self.walls)
119
[145]120 def add_game_objects(self):
[191]121 for drawable in self._level.drawables:
[145]122 self._drawables.add(drawable)
123
[37]124 def add_protagonist(self):
[276]125 self.protagonist = self.world.protagonist
126 self.protagonist.change_space(self.space)
[107]127 self._drawables.add(self.protagonist)
[21]128
[18]129 def handle_event(self, ev):
[20]130 if ev.type == pygame.locals.KEYDOWN:
131 if ev.key == pygame.locals.K_ESCAPE:
132 ScreenChange.post('menu')
[97]133 if ev.key == pygame.locals.K_c:
[47]134 self.protagonist.toggle_form()
[238]135 self.world.transformations += 1
[283]136 if ev.key in (pygame.locals.K_z, pygame.locals.K_LCTRL):
[261]137 self.world.attacks += 1
138 self.protagonist.attack()
[281]139 if ev.key == pygame.locals.K_SPACE:
140 self.protagonist.perform_action()
[180]141 elif DoorEvent.matches(ev):
142 self.protagonist.set_position(ev.dest_pos)
143 if ev.destination != self.name:
144 # Go to anther screen
[190]145 self._disable_render = True
[238]146 self.world.rooms += 1
[276]147 ScreenChange.post(ev.destination)
[190]148 return
[180]149 # else we're teleporting within the screen, and just the
150 # position change is enough
[261]151 elif FireEvent.matches(ev):
[305]152 bullet = Bullet(self.space, ev.source, ev.impulse, ev.damage,
[293]153 ev.source_collision_type)
[261]154 self._drawables.add(bullet)
[308]155 elif EnemyDeathEvent.matches(ev):
156 self.world.kills += 1
157 dead_enemy = DeadEnemy(self.space, self.world, ev.position,
158 ev.enemy_type)
159 self._drawables.add(dead_enemy)
[312]160 elif ClawEvent.matches(ev):
161 claw_attack = ClawAttack(self.space, ev.source, ev.vector,
162 ev.source_collision_type)
163 self._drawables.add(claw_attack)
[34]164 self.keys.handle_event(ev)
[18]165
[87]166 def _calc_viewport(self, level_surface, display_surface):
167 level_size = level_surface.get_size()
168 display_size = display_surface.get_size()
[93]169 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]170 level_surface)
[87]171 x_wide = display_size[0] // 2
172 y_wide = display_size[1] // 2
[127]173 if display_size[0] > level_size[0]:
174 x = -(display_size[0] - level_size[0]) // 2
175 elif protagnist_pos[0] < x_wide:
[87]176 x = 0
177 elif protagnist_pos[0] > level_size[0] - x_wide:
178 x = level_size[0] - display_size[0]
179 else:
180 x = protagnist_pos[0] - x_wide
[127]181 if display_size[1] > level_size[1]:
182 y = -(display_size[1] - level_size[1]) // 2
183 elif protagnist_pos[1] < y_wide:
[87]184 y = 0
185 elif protagnist_pos[1] > level_size[1] - y_wide:
186 y = level_size[1] - display_size[1]
187 else:
188 y = protagnist_pos[1] - y_wide
189 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
190
[18]191 def render(self, surface):
[190]192 if self._disable_render:
193 return
[50]194 background = self._level.get_background()
[84]195 mysurface = background.copy()
[105]196 for drawable in self._drawables:
197 drawable.render(mysurface)
[87]198 render_rect = self._calc_viewport(mysurface, surface)
199 surface.blit(mysurface, (0, 0), render_rect)
[191]200 for overlay in self._level.overlay_drawables:
201 if overlay.is_visible():
[211]202 overlay.render(surface, render_rect.topleft)
[243]203 self.render_health_bar(surface)
[34]204
205 def tick_protagonist(self):
[100]206 dx, dy = self.keys.get_direction()
[47]207 self.protagonist.set_direction(dx, dy)
[34]208
209 def tick(self, seconds):
[303]210 super(AreaScreen, self).tick(seconds)
[34]211 self.tick_protagonist()
[143]212 for drawable in self._drawables:
[307]213 drawable.update(seconds)
[293]214 if drawable.remove:
215 self._drawables.remove(drawable)
[243]216
[258]217 def render_health_bar(self, surface, damage_experienced=None):
[243]218 rect = pygame.Rect(50, 500, 110, 50)
[258]219 if damage_experienced:
220 health_box_colour = pygame.color.THECOLORS['red']
221 else:
222 health_box_colour = pygame.color.THECOLORS['white']
[257]223 pygame.draw.rect(surface, health_box_colour, rect, 0)
[246]224 if self.protagonist.in_human_form():
[243]225 health_colour = pygame.color.THECOLORS['red']
226 else:
227 health_colour = pygame.color.THECOLORS['purple']
[246]228 rect = pygame.Rect(55, 505, self.protagonist.get_health_level(), 40)
[243]229 pygame.draw.rect(surface, health_colour,
[246]230 rect, 0)
Note: See TracBrowser for help on using the repository browser.