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