source: nagslang/screens/area.py@ 34:2995723e8ccf

Last change on this file since 34:2995723e8ccf was 34:2995723e8ccf, checked in by Simon Cross <hodgestar@…>, 8 years ago

Move and hold.

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