Display power usage per hour.
[tabakrolletjie.git] / tabakrolletjie / scenes / day.py
1 """ Be prepared. """
2
3 import math
4
5 import pygame.display
6 import pygame.surface
7 import pygame.locals as pgl
8
9 import pymunk
10 import pymunk.pygame_util
11
12 from .base import BaseScene
13 from ..battery import BatteryManager
14 from ..lights import LightManager, light_fitting_by_type
15 from ..infobar import InfoBar
16 from ..obstacles import ObstacleManager
17 from ..events import SceneChangeEvent
18 from ..utils import debug_timer, shadowed_text
19 from ..loader import loader
20 from ..transforms import Overlay, Alpha, ColourWedges
21
22 from ..constants import SCREEN_SIZE, FONTS, FPS, NIGHT_HOURS_PER_TICK, DEBUG
23 from ..widgets import ImageButton
24 from ..turnip import Turnip, TurnipInvalidPosition, check_turnips
25
26
27 class DayScene(BaseScene):
28
29     BRIGHTNESS = Overlay(colour=(255, 255, 255, 50))
30
31     def enter(self, gamestate):
32         self._space = pymunk.Space()
33         self._obstacles = ObstacleManager(self._space, gamestate)
34         self._lights = LightManager(self._space, gamestate)
35         self._battery = BatteryManager(gamestate)
36         self._infobar = InfoBar("day", battery=self._battery, scene=self)
37         self._turnips = []
38         self._paused = False
39         self._tool = None
40         self._light_colors = None
41         self._dragging = None
42         # Turnip
43         self.grow_turnips(gamestate)
44         # Tools
45         self._light_toolbar = []
46         self._tools = self.create_tools(gamestate)
47         # Background
48         self._soil = loader.load_image(
49             "textures", "soil.png", transform=self.BRIGHTNESS)
50         # Check if we've lost
51         self._game_over_text = []
52         if gamestate.seeds == 0 and len(self._turnips) == 0:
53             self._draw_you_lose(gamestate)
54         elif gamestate.harvested >= gamestate.turnip_target:
55             self._draw_you_win(gamestate)
56
57     def _draw_you_lose(self, gamestate):
58         overlay = pygame.surface.Surface(
59             (SCREEN_SIZE[0], 240), pgl.SWSURFACE).convert_alpha()
60         overlay.fill((0, 0, 0, 128))
61         self._game_over_text.append((overlay, (0, 250)))
62         self._game_over_text.append(
63             (shadowed_text("You Lost", FONTS["bold"], 48), (400, 280)))
64         self._game_over_text.append(
65             (shadowed_text("You have no seeds and no turnips growing",
66                            FONTS["sans"], 24), (300, 350)))
67         self._game_over_text.append(
68             (shadowed_text("Press a key to return to the menu",
69                            FONTS["sans"], 24), (350, 400)))
70
71     def _draw_you_win(self, gamestate):
72         overlay = pygame.surface.Surface(
73             (SCREEN_SIZE[0], 240), pgl.SWSURFACE).convert_alpha()
74         overlay.fill((0, 0, 0, 128))
75         self._game_over_text.append((overlay, (0, 250)))
76         self._game_over_text.append(
77             (shadowed_text("You Win", FONTS["bold"], 48), (400, 280)))
78         self._game_over_text.append(
79             (shadowed_text(
80                 ("You have Successfully Harvested %d turnips" %
81                  gamestate.harvested),
82                 FONTS["sans"], 24),
83              (300, 350)))
84         self._game_over_text.append(
85             (shadowed_text("Press a key to return to the menu",
86                            FONTS["sans"], 24), (350, 400)))
87
88     def grow_turnips(self, gamestate):
89         for turnip_data in gamestate.turnips:
90             turnip = Turnip(space=self._space, **turnip_data)
91             # Turnips grow at dawn
92             seeds = turnip.grow()
93             if seeds:
94                 gamestate.seeds += seeds
95                 gamestate.harvested += 1
96             else:
97                 self._turnips.append(turnip)
98
99     def create_tools(self, gamestate):
100         tools = []
101
102         x, y, step = 50, SCREEN_SIZE[1] - 40, 50
103
104         tools.append(ImageButton('32', 'seed.png', name='seed', pos=(x, y)))
105         x += step
106
107         for light_config in gamestate.station["available_lights"]:
108             tool = ImageButton(
109                 '32', '%s.png' % light_config["type"], name='light',
110                 pos=(x, y))
111             tool.light_config = light_config
112             tools.append(tool)
113             x += step
114
115         tools.append(ImageButton(
116             '32', 'default_cursor.png', name='reset tool', pos=(x, y)))
117
118         tools.append(ImageButton(
119             '32', 'night.png', name='start night',
120             pos=(SCREEN_SIZE[0] - 100, y)))
121         tools.append(ImageButton(
122             '32', 'exit.png', name='exit', pos=(SCREEN_SIZE[0] - 50, y)))
123         return tools
124
125     def exit(self, gamestate):
126         self._unset_cursor()
127         turnip_data = [turnip.serialize() for turnip in self._turnips]
128         gamestate.turnips = turnip_data
129
130     def end_day(self, gamestate):
131         self._battery.apply_recharge()
132         from .night import NightScene
133         SceneChangeEvent.post(scene=NightScene())
134
135     @property
136     def turnip_count(self):
137         return len(self._turnips)
138
139     @property
140     def power_usage(self):
141         power = self._lights.total_power_usage()
142         power = power / (FPS * NIGHT_HOURS_PER_TICK)
143         return int(round(power))
144
145     @debug_timer("day.render")
146     def render(self, surface, gamestate):
147         surface.blit(self._soil, (0, 0))
148
149         for turnip in self._turnips:
150             turnip.render(surface)
151         self._lights.render_light(surface)
152         self._obstacles.render(surface)
153         self._lights.render_fittings(surface)
154         self._infobar.render(surface, gamestate)
155         for tool in self._tools:
156             tool.render(surface)
157         for light_tool in self._light_toolbar:
158             light_tool.render(surface)
159         self._draw_cursor(surface)
160         if self._game_over_text:
161             for surf, pos in self._game_over_text:
162                 surface.blit(surf, pos)
163
164     def _draw_light_toolbar(self, light_config, x):
165         height = SCREEN_SIZE[1] - 80
166         self._light_toolbar = []
167         colour_combos = light_config["available_colours"]
168         for combo in colour_combos:
169             colours = combo.split("/")
170             light_fitting = light_fitting_by_type(light_config["type"])
171             light_tool = ImageButton(
172                 "32", light_fitting, transform=ColourWedges(colours=colours),
173                 pos=(x, height), name=combo)
174             light_tool.colours = colours
175             self._light_toolbar.append(light_tool)
176             x += 40
177
178     def _clear_light_toolbar(self):
179         self._light_toolbar = []
180
181     def _place_seed(self, gamestate, ev):
182         if gamestate.seeds > 0:
183             # plant seed
184             # We don't want top-left to equal the mouse position,
185             # since that looks weird, but we don't want to center
186             # the turnip under the mouse either, since that
187             # causes issues as well, so we compromise
188             pos = (ev.pos[0] - 18, ev.pos[1] - 18)
189             try:
190                 turnip = Turnip(age=0, pos=pos, space=self._space)
191                 self._turnips.append(turnip)
192                 gamestate.seeds -= 1
193             except TurnipInvalidPosition:
194                 # TODO: Add error sound or something
195                 pass
196
197     def _update_light_angle(self, pos, gamestate):
198         # Update the angle of the given light
199         pos = pymunk.pygame_util.to_pygame(pos, pygame.display.get_surface())
200         distance = pos - self._dragging.position
201         angle = math.atan2(distance[1], distance[0])
202         # Set light angle to this position
203         self._dragging.ray_manager.direction = math.degrees(angle)
204         # Hackily update gamestate with new angle
205         for light_cfg in gamestate.station["lights"]:
206             light_pos = pymunk.Vec2d(light_cfg["position"])
207             if light_pos.get_dist_sqrd(self._dragging.position) < 5.0:
208                 light_cfg["direction"] = math.degrees(angle)
209                 break
210
211     def _place_light(self, gamestate, cfg, colours, ev):
212         cfg = cfg.copy()
213         cost = cfg.pop("cost")
214         cfg.pop("available_colours")
215         if gamestate.seeds > cost:
216             pos = pymunk.pygame_util.from_pygame(
217                 ev.pos, pygame.display.get_surface())
218             # Bail if we're too close to an existing light
219             if self._lights.nearest(pos, max_distance=25):
220                 return
221             # Also check turnips
222             if check_turnips(self._space, pos, max_distance=25):
223                 return
224             gamestate.seeds -= cost
225             cfg["position"] = pos
226             cfg["colours"] = colours
227             gamestate.station["lights"].append(cfg)
228             self._lights.add_light(cfg)
229
230     def event(self, ev, gamestate):
231         if self._game_over_text:
232             if ev.type in (pgl.KEYDOWN, pgl.MOUSEBUTTONDOWN):
233                 from .menu import MenuScene
234                 SceneChangeEvent.post(scene=MenuScene())
235         if ev.type == pgl.KEYDOWN:
236             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
237                 from .menu import MenuScene
238                 SceneChangeEvent.post(scene=MenuScene())
239             elif ev.key == pgl.K_e:
240                 self.end_day(gamestate)
241             elif ev.key == pgl.K_SPACE and DEBUG:
242                 self._paused = not self._paused
243         elif ev.type == pgl.MOUSEBUTTONDOWN:
244             if ev.button == 1:
245                 # Check tools
246                 for tool in self._tools:
247                     if tool.pressed(ev):
248                         self._color = None
249                         if tool.name == 'reset tool':
250                             self._unset_cursor()
251                             self._tool = None
252                             self._clear_light_toolbar()
253                         elif tool.name == 'start night':
254                             self.end_day(gamestate)
255                         elif tool.name == 'exit':
256                             from .menu import MenuScene
257                             SceneChangeEvent.post(scene=MenuScene())
258                         else:
259                             self._tool = tool
260                             if self._tool.name == 'seed':
261                                 self._set_cursor(
262                                     'seed', transform=Alpha(alpha=172))
263                                 self._clear_light_toolbar()
264                             elif self._tool.name == 'light':
265                                 self._unset_cursor()
266                                 self._draw_light_toolbar(
267                                     self._tool.light_config, 100)
268                         return
269                 # Check light toolbar
270                 for light_tool in self._light_toolbar:
271                     if light_tool.pressed(ev):
272                         fitting_image = light_fitting_by_type(
273                             self._tool.light_config["type"])
274                         self._set_cursor(
275                             fitting_image[:-4],  # strip .png
276                             transform=ColourWedges(colours=light_tool.colours))
277                         # colour=COLOURS[0] + (172,)))
278                         self._light_colors = light_tool.colours
279                         return
280                 if self._tool:
281                     if self._tool.name == "seed":
282                         self._place_seed(gamestate, ev)
283                     elif self._tool.name == "light" and self._light_colors:
284                         self._place_light(
285                             gamestate, self._tool.light_config,
286                             self._light_colors, ev)
287                 else:
288                     # Not tool, so check lights
289                     self._lights.toggle_nearest(ev.pos, surfpos=True)
290             elif ev.button == 3:
291                 light = self._lights.nearest(ev.pos, surfpos=True,
292                                              max_distance=20.0)
293                 if light:
294                     # Start drag to rotate light
295                     self._dragging = light
296                 elif self._tool:
297                     # Unset tool
298                     self._tool = None
299                     self._clear_light_toolbar()
300                     self._unset_cursor()
301         elif ev.type == pgl.MOUSEMOTION:
302             if self._dragging:
303                 # Calculate angle between current position and mouse pos
304                 self._update_light_angle(ev.pos, gamestate)
305         elif ev.type == pgl.MOUSEBUTTONUP:
306             self._dragging = None
307
308     @debug_timer("day.tick")
309     def tick(self, gamestate):
310         if not self._paused:
311             self._lights.tick()