source: nagslang/screens/area.py@ 35:457280af5f3a

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

Remove unused import.

File size: 2.5 KB
Line 
1"""Display a game area."""
2
3import pygame
4import pymunk
5import pymunk.pygame_util
6
7from nagslang.screens.base import Screen
8from nagslang.events import ScreenChange
9
10
11class ControlKeys(object):
12 def __init__(self):
13 self.keys_down = set()
14
15 def key_down(self, key):
16 self.keys_down.add(key)
17
18 def key_up(self, key):
19 self.keys_down.discard(key)
20
21 def handle_event(self, ev):
22 if ev.type == pygame.locals.KEYDOWN:
23 self.key_down(ev.key)
24 elif ev.type == pygame.locals.KEYUP:
25 self.key_up(ev.key)
26
27
28class AreaScreen(Screen):
29
30 def setup(self, world):
31 self.keys = ControlKeys()
32 self.add_walls(world)
33 self.add_protagonist(world)
34
35 def add_walls(self, world):
36 self.walls = []
37 body = pymunk.Body()
38 body.position = (400, 300)
39 corners = [(-200, -150), (-200, 150), (200, 150), (200, -150)]
40 corner = corners[-1]
41 for next_corner in corners:
42 self.walls.append(pymunk.Segment(body, corner, next_corner, 5))
43 corner = next_corner
44 self.space.add(*self.walls)
45
46 def add_protagonist(self, world):
47 self.protagonist_body = pymunk.Body(100, 1000)
48 self.protagonist_body.position = (400, 300)
49 self.protagonist_body.velocity_limit = 5000
50 self.protagonist = pymunk.Circle(self.protagonist_body, 30)
51 self.space.add(self.protagonist_body, self.protagonist)
52
53 def protagonist_move(self, dx, dy):
54 vec = pymunk.Vec2d((dx, dy))
55 self.protagonist_body.angle = vec.angle
56 self.protagonist_body.apply_impulse((dx * 1000, dy * 1000))
57
58 def handle_event(self, ev):
59 if ev.type == pygame.locals.KEYDOWN:
60 if ev.key == pygame.locals.K_ESCAPE:
61 ScreenChange.post('menu')
62 self.keys.handle_event(ev)
63
64 def render(self, surface):
65 surface.fill(pygame.color.Color(0, 0, 0))
66 pymunk.pygame_util.draw(surface, *self.walls)
67 pymunk.pygame_util.draw(surface, self.protagonist)
68
69 def tick_protagonist(self):
70 dx, dy = 0, 0
71 for key, tx, ty in [
72 (pygame.locals.K_UP, 0, 1), (pygame.locals.K_DOWN, 0, -1),
73 (pygame.locals.K_LEFT, -1, 0), (pygame.locals.K_RIGHT, 1, 0)
74 ]:
75 if key in self.keys.keys_down:
76 dx += tx
77 dy += ty
78 self.protagonist_move(dx, dy)
79
80 def tick(self, seconds):
81 self.tick_protagonist()
82 super(AreaScreen, self).tick(seconds)
Note: See TracBrowser for help on using the repository browser.