Allow people to go back to the menu.
[tabakrolletjie.git] / tabakrolletjie / scenes / load_level.py
1 """ Menu scene. """
2
3 import os
4
5 import pygame.locals as pgl
6
7 from .base import BaseScene
8 from ..events import SceneChangeEvent
9 from ..widgets import TextButton
10 from ..loader import loader
11
12
13 class LoadLevelScene(BaseScene):
14
15     def _list_stations(self):
16         station_path = loader.full_path("stations")
17         files = [f for f in os.listdir(station_path) if f.endswith(".json")]
18         files.sort()
19         return [loader.load_station(f) for f in files]
20
21     def enter(self, gamestate):
22         """Construct list of stations"""
23         height = 50
24         width = 30
25         self._buttons = []
26         for station in self._list_stations():
27             title = station["config"]["name"]
28             pos = (width, height)
29             button = TextButton(title, (255, 255, 255), None, pos)
30             button.station = station
31             if width < 400:
32                 width += 350
33             else:
34                 width = 30
35                 height += button.get_height() + 20
36             self._buttons.append(button)
37
38     def render(self, surface, gamestate):
39         surface.fill((0, 128, 128))
40         for button in self._buttons:
41             button.render(surface)
42
43     def _get_pressed(self, ev):
44         for button in self._buttons:
45             if button.pressed(ev):
46                 return button
47         return None
48
49     def _do_load(self, station, gamestate):
50         from .day import DayScene
51         print "Loading station", station["config"]["name"]
52         gamestate.set_station(station)
53         SceneChangeEvent.post(scene=DayScene())
54
55     def event(self, ev, gamestate):
56         if ev.type == pgl.KEYDOWN:
57             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
58                 from .menu import MenuScene
59                 SceneChangeEvent.post(scene=MenuScene())
60         elif ev.type == pgl.MOUSEBUTTONDOWN:
61             pressed = self._get_pressed(ev)
62             if pressed:
63                 self._do_load(pressed.station, gamestate)