4506edf6e1e91d66dc89ee1091b83bcbe92c81db
[naja.git] / naja / widgets / robot.py
1 """Widget to draw the player on the screen"""
2
3 import pygame.locals as pgl
4
5 from naja.constants import PLAYER_SIZE, BIT_SIZE, TILE_SIZE, BITS
6 from naja.events import InvalidateTheWorld
7 from naja.resources import resources
8 from naja.resources.mutators import EIGHT_BIT
9 from naja.widgets.base import Widget
10
11 IMG_MAP = {
12         BITS.CYAN: 'board/robot_cyan.png',
13         BITS.YELLOW: 'board/robot_yellow.png',
14         BITS.MAGENTA: 'board/robot_magenta.png',
15         }
16
17
18 class RobotWidget(Widget):
19     """Widget which holds a tile on the game board."""
20     def __init__(self, state):
21         pos = (state.player.position[0] * TILE_SIZE[0] + 32,
22                state.player.position[1] * TILE_SIZE[1] + BIT_SIZE[1])
23         super(RobotWidget, self).__init__(pos, PLAYER_SIZE)
24         self.state = state
25
26     def prepare(self):
27         # Look up the required bits on the board location
28         self.pos = (self.state.player.position[0] * TILE_SIZE[0] + 32,
29                     self.state.player.position[1] * TILE_SIZE[1] + BIT_SIZE[1])
30         self.surface = resources.get_image('board/robot.png',
31                                            transforms=(EIGHT_BIT,))
32         for bit, img_name in IMG_MAP.iteritems():
33             if self.state.player.bits.check_bit(bit):
34                 bit_img = resources.get_image(img_name,
35                                               transforms=(EIGHT_BIT,))
36                 self.surface.blit(bit_img, (0, 0))
37
38     def draw(self, surface):
39         surface.blit(self.surface, self.rect)
40
41     def handle_event(self, ev):
42         if ev.type == pgl.KEYDOWN:
43             if ev.key in (pgl.K_UP, pgl.K_w):
44                 if self.state.player.move(BITS.NORTH):
45                     InvalidateTheWorld.post()
46                     return True
47             if ev.key in (pgl.K_DOWN, pgl.K_s):
48                 if self.state.player.move(BITS.SOUTH):
49                     InvalidateTheWorld.post()
50                     return True
51             if ev.key in (pgl.K_LEFT, pgl.K_a):
52                 if self.state.player.move(BITS.WEST):
53                     InvalidateTheWorld.post()
54                     return True
55             if ev.key in (pgl.K_RIGHT, pgl.K_d):
56                 if self.state.player.move(BITS.EAST):
57                     InvalidateTheWorld.post()
58                     return True
59         super(RobotWidget, self).handle_event(ev)