dcbc74498b930b3e4d2b31aa6318eae7d59d6b57
[naja.git] / naja / widgets / selector.py
1 import pygame.locals as pgl
2
3 from naja.constants import KEYS
4 from naja.widgets.base import Container
5 from naja.resources import resources
6 from naja.resources.mutators import EIGHT_BIT, R270
7 from naja.sound import sound
8
9
10 class SelectorWidget(Container):
11     def __init__(self, *args, **kwargs):
12         super(SelectorWidget, self).__init__(*args, **kwargs)
13         self.position = 0
14         self.selector = resources.get_image('bits', 'arrow_on.png',
15                                             transforms=(R270, EIGHT_BIT))
16
17     def render(self, surface):
18         super(SelectorWidget, self).render(surface)
19         pos = self.selector.get_rect()
20         selected = self.widgets[self.position]
21         if not selected.is_selectable():
22             selected = self.change_pos(1)
23
24         pos = pos.move(selected.pos)
25         pos = pos.move(-pos.width * 1.5, (selected.size[1] - pos.height) / 2)
26         surface.blit(self.selector, pos)
27
28     def change_pos(self, change):
29         self.position = (self.position + change) % len(self.widgets)
30         while not self.widgets[self.position].is_selectable():
31             self.position = (self.position + change) % len(self.widgets)
32         return self.widgets[self.position]
33
34     def handle_event(self, ev):
35         if ev.type == pgl.KEYDOWN:
36             if ev.key in KEYS.UP + KEYS.DOWN:
37                 if ev.key in KEYS.DOWN:
38                     self.change_pos(1)
39                 else:
40                     self.change_pos(-1)
41                 sound.play_sound('zoop.ogg', volume=0.05)
42                 return True
43             elif ev.key in KEYS.SELECT:
44                 return self.widgets[self.position].callback('click')
45
46         return super(SelectorWidget, self).handle_event(ev)