Populate toolbar from available lights.
[tabakrolletjie.git] / tabakrolletjie / scenes / day.py
1 """ Be prepared. """
2
3 import math
4
5 import pygame.display
6 import pygame.locals as pgl
7
8 import pymunk
9 import pymunk.pygame_util
10
11 from .base import BaseScene
12 from ..lights import LightManager
13 from ..obstacles import ObstacleManager
14 from ..events import SceneChangeEvent
15 from ..utils import debug_timer
16 from ..loader import loader
17 from ..transforms import Overlay, Multiply, Alpha
18
19 from ..constants import SCREEN_SIZE, FONTS, COLOURS
20 from ..widgets import ImageButton
21 from ..turnip import Turnip, TurnipInvalidPosition
22
23
24 class DayScene(BaseScene):
25
26     BRIGHTNESS = Overlay(colour=(255, 255, 255, 50))
27
28     def enter(self, gamestate):
29         self._space = pymunk.Space()
30         self._toolbar_font = loader.load_font(FONTS['sans'], size=20)
31         self._obstacles = ObstacleManager(self._space, gamestate)
32         self._lights = LightManager(self._space, gamestate)
33         self._turnips = []
34         self._seeds = gamestate.seeds
35         self._harvested = gamestate.harvested
36         self._paused = False
37         self._tool = None
38         self._light_color = None
39         self._dragging = None
40         # Turnip
41         self.grow_turnips(gamestate)
42         # Tools
43         self._light_toolbar = []
44         self._tools = self.create_tools(gamestate)
45         self._update_toolbar(gamestate)
46         # Background
47         self._soil = loader.load_image(
48             "textures", "soil.png", transform=self.BRIGHTNESS)
49
50     def grow_turnips(self, gamestate):
51         for turnip_data in gamestate.turnips:
52             turnip = Turnip(space=self._space, **turnip_data)
53             # Turnips grow at dawn
54             seeds = turnip.grow()
55             if seeds:
56                 self._seeds += seeds
57                 self._harvested += 1
58             else:
59                 self._turnips.append(turnip)
60
61     def create_tools(self, gamestate):
62         tools = []
63         x, y, step = 50, SCREEN_SIZE[1] - 40, 50
64         tools.append(ImageButton('32', 'seed.png', name='seed', pos=(x, y)))
65         x += step
66
67         for light_config in gamestate.station["available_lights"]:
68             tool = ImageButton(
69                 '32', '%s.png' % light_config["type"], name='light',
70                 pos=(x, y))
71             tool.light_config = light_config
72             tools.append(tool)
73             x += step
74
75         tools.append(ImageButton(
76             '32', 'default_cursor.png', name='reset tool', pos=(x, y)))
77         return tools
78
79     def exit(self, gamestate):
80         self._unset_cursor()
81         gamestate.seeds = self._seeds
82         gamestate.harvested = self._harvested
83         turnip_data = [turnip.serialize() for turnip in self._turnips]
84         gamestate.turnips = turnip_data
85
86     @debug_timer("day.render")
87     def render(self, surface, gamestate):
88         surface.blit(self._soil, (0, 0))
89
90         for turnip in self._turnips:
91             turnip.render(surface)
92         self._lights.render_light(surface)
93         self._obstacles.render(surface)
94         self._lights.render_fittings(surface)
95         surface.blit(self._toolbar, (120, 10), None)
96         for tool in self._tools:
97             tool.render(surface)
98         for light_tool in self._light_toolbar:
99             light_tool.render(surface)
100         self._draw_cursor(surface)
101
102     def _draw_light_toolbar(self, light_config, x):
103         self._light_toolbar = []
104         height = SCREEN_SIZE[1] - 80
105         for color in sorted(COLOURS.keys()):
106             light_tool = ImageButton('32', light_config["type"] + '.png',
107                                      pos=(x, height), name=color,
108                                      transform=Multiply(colour=COLOURS[color]))
109             self._light_toolbar.append(light_tool)
110             x += 40
111
112     def _clear_light_toolbar(self):
113         self._light_toolbar = []
114
115     def _place_seed(self, gamestate, ev):
116         if self._seeds > 0:
117             # plant seed
118             # We don't want top-left to equal the mouse position,
119             # since that looks weird, but we don't want to center
120             # the turnip under the mouse either, since that
121             # causes issues as well, so we compromise
122             pos = (ev.pos[0] - 8, ev.pos[1] - 8)
123             try:
124                 turnip = Turnip(age=0, pos=pos, space=self._space)
125                 self._turnips.append(turnip)
126                 self._seeds -= 1
127                 self._update_toolbar(gamestate)
128             except TurnipInvalidPosition:
129                 # TODO: Add error sound or something
130                 pass
131
132     def _update_light_angle(self, pos, gamestate):
133         # Update the angle of the given light
134         pos = pymunk.pygame_util.to_pygame(pos, pygame.display.get_surface())
135         distance = pos - self._dragging.position
136         angle = math.atan2(distance[1], distance[0])
137         # Set light angle to this position
138         self._dragging.ray_manager.direction = math.degrees(angle)
139         # Hackily update gamestate with new angle
140         for light_cfg in gamestate.station["lights"]:
141             light_pos = pymunk.Vec2d(light_cfg["position"])
142             if light_pos.get_dist_sqrd(self._dragging.position) < 5.0:
143                 light_cfg["direction"] = math.degrees(angle)
144                 break
145
146     def _place_light(self, gamestate, cfg, colours, ev):
147         cfg = cfg.copy()
148         cost = cfg.pop("cost")
149         if self._seeds > cost:
150             pos = pymunk.pygame_util.from_pygame(
151                 ev.pos, pygame.display.get_surface())
152             # Bail if we're too close to an existing light
153             if self._lights.nearest(pos, max_distance=25):
154                 return
155             self._seeds -= cost
156             self._update_toolbar(gamestate)
157             cfg["position"] = pos
158             cfg["colours"] = colours
159             gamestate.station["lights"].append(cfg)
160             self._lights.add_light(cfg)
161
162     def event(self, ev, gamestate):
163         if ev.type == pgl.KEYDOWN:
164             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
165                 from .menu import MenuScene
166                 SceneChangeEvent.post(scene=MenuScene())
167             elif ev.key == pgl.K_e:
168                 from .night import NightScene
169                 SceneChangeEvent.post(scene=NightScene())
170             elif ev.key == pgl.K_SPACE:
171                 self._paused = not self._paused
172         elif ev.type == pgl.MOUSEBUTTONDOWN:
173             if ev.button == 1:
174                 # Check tools
175                 for tool in self._tools:
176                     if tool.pressed(ev):
177                         self._color = None
178                         if tool.name == 'reset tool':
179                             self._unset_cursor()
180                             self._tool = None
181                             self._clear_light_toolbar()
182                         else:
183                             self._tool = tool
184                             if self._tool.name == 'seed':
185                                 self._set_cursor(
186                                     'seed', transform=Alpha(alpha=172))
187                                 self._clear_light_toolbar()
188                             elif self._tool.name == 'light':
189                                 self._unset_cursor()
190                                 self._draw_light_toolbar(
191                                     self._tool.light_config, 100)
192                         return
193                 # Check light toolbar
194                 for light_tool in self._light_toolbar:
195                     if light_tool.pressed(ev):
196                         self._set_cursor(
197                             self._tool.light_config["type"],
198                             transform=Multiply(
199                                 colour=COLOURS[light_tool.name] + (172,)))
200                         self._light_color = light_tool.name
201                         return
202                 if self._tool.name == "seed":
203                     self._place_seed(gamestate, ev)
204                 elif self._tool.name == "light" and self._light_color:
205                     self._place_light(
206                         gamestate, self._tool.light_config,
207                         [self._light_color], ev)
208                 else:
209                     # Not tool, so check lights
210                     self._lights.toggle_nearest(ev.pos, surfpos=True)
211             elif ev.button == 3:
212                 light = self._lights.nearest(ev.pos, surfpos=True,
213                                              max_distance=20.0)
214                 if light:
215                     # Start drag to rotate light
216                     self._dragging = light
217                 elif self._tool:
218                     # Unset tool
219                     self._tool = None
220                     self._unset_cursor()
221         elif ev.type == pgl.MOUSEMOTION:
222             if self._dragging:
223                 # Calculate angle between current position and mouse pos
224                 self._update_light_angle(ev.pos, gamestate)
225         elif ev.type == pgl.MOUSEBUTTONUP:
226             self._dragging = None
227
228     @debug_timer("day.tick")
229     def tick(self, gamestate):
230         if not self._paused:
231             self._lights.tick()
232
233     def _update_toolbar(self, gamestate):
234         text = ("Turnip Stocks: Seeds: %d. Planted: %d. "
235                 "Harvested: %d. Destroyed: %d" %
236                 (self._seeds, len(self._turnips),
237                  self._harvested, gamestate.eaten))
238         self._toolbar = self._toolbar_font.render(text, True, (255, 255, 255))