7f73ad288a17342946d91a928577220da0e86ddb
[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, check_space_for_light
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
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         self._ending = False
57
58     def _draw_you_lose(self, gamestate):
59         overlay = pygame.surface.Surface(
60             (SCREEN_SIZE[0], 240), pgl.SWSURFACE).convert_alpha()
61         overlay.fill((0, 0, 0, 128))
62         self._game_over_text.append((overlay, (0, 250)))
63         self._game_over_text.append(
64             (shadowed_text("You Lost", FONTS["bold"], 48), (400, 280)))
65         self._game_over_text.append(
66             (shadowed_text("You have no seeds and no turnips growing",
67                            FONTS["sans"], 24), (300, 350)))
68         self._game_over_text.append(
69             (shadowed_text("Press a key to return to the menu",
70                            FONTS["sans"], 24), (350, 400)))
71
72     def _draw_you_win(self, gamestate):
73         overlay = pygame.surface.Surface(
74             (SCREEN_SIZE[0], 240), pgl.SWSURFACE).convert_alpha()
75         overlay.fill((0, 0, 0, 128))
76         self._game_over_text.append((overlay, (0, 250)))
77         self._game_over_text.append(
78             (shadowed_text("You Win", FONTS["bold"], 48), (400, 280)))
79         self._game_over_text.append(
80             (shadowed_text(
81                 ("You have Successfully Harvested %d turnips" %
82                  gamestate.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                 gamestate.seeds += seeds
96                 gamestate.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         turnip_data = [turnip.serialize() for turnip in self._turnips]
129         gamestate.turnips = turnip_data
130
131     def end_day(self, gamestate):
132         if self._ending:
133             return
134         self._battery.apply_recharge()
135         gamestate.update_lights(self._lights)
136         self._ending = True
137         from .night import NightScene
138         SceneChangeEvent.post(scene=NightScene())
139
140     @property
141     def turnip_count(self):
142         return len(self._turnips)
143
144     @property
145     def power_usage(self):
146         power = self._lights.total_power_usage()
147         power = power / (FPS * NIGHT_HOURS_PER_TICK)
148         return int(round(power))
149
150     @debug_timer("day.render")
151     def render(self, surface, gamestate):
152         surface.blit(self._soil, (0, 0))
153
154         for turnip in self._turnips:
155             turnip.render(surface)
156         self._lights.render_light(surface)
157         self._obstacles.render(surface)
158         self._lights.render_fittings(surface)
159         self._infobar.render(surface, gamestate)
160         for tool in self._tools:
161             tool.render(surface)
162         for light_tool in self._light_toolbar:
163             light_tool.render(surface)
164         self._draw_cursor(surface)
165         if self._game_over_text:
166             for surf, pos in self._game_over_text:
167                 surface.blit(surf, pos)
168
169     def _draw_light_toolbar(self, light_config, x):
170         height = SCREEN_SIZE[1] - 80
171         self._light_toolbar = []
172         colour_combos = light_config["available_colours"]
173         for combo in colour_combos:
174             colours = combo.split("/")
175             light_fitting = light_fitting_by_type(light_config["type"])
176             light_tool = ImageButton(
177                 "32", light_fitting, transform=ColourWedges(colours=colours),
178                 pos=(x, height), name=combo)
179             light_tool.colours = colours
180             self._light_toolbar.append(light_tool)
181             x += 40
182
183     def _clear_light_toolbar(self):
184         self._light_toolbar = []
185
186     def _place_seed(self, gamestate, ev):
187         if gamestate.seeds > 0:
188             # plant seed
189             # We don't want top-left to equal the mouse position,
190             # since that looks weird, but we don't want to center
191             # the turnip under the mouse either, since that
192             # causes issues as well, so we compromise
193             pos = (ev.pos[0] - 18, ev.pos[1] - 18)
194             try:
195                 turnip = Turnip(age=0, pos=pos, space=self._space)
196                 self._turnips.append(turnip)
197                 gamestate.seeds -= 1
198             except TurnipInvalidPosition:
199                 # TODO: Add error sound or something
200                 pass
201
202     def _update_light_angle(self, pos, gamestate):
203         # Update the angle of the given light
204         pos = pymunk.pygame_util.to_pygame(pos, pygame.display.get_surface())
205         distance = pos - self._dragging.position
206         angle = math.atan2(distance[1], distance[0])
207         # Set light angle to this position
208         self._dragging.ray_manager.direction = math.degrees(angle)
209         # Hackily update gamestate with new angle
210         for light_cfg in gamestate.station["lights"]:
211             light_pos = pymunk.Vec2d(light_cfg["position"])
212             if light_pos.get_dist_sqrd(self._dragging.position) < 5.0:
213                 light_cfg["direction"] = math.degrees(angle)
214                 break
215
216     def _place_light(self, gamestate, cfg, colours, ev):
217         cfg = cfg.copy()
218         cost = cfg.pop("cost")
219         cfg.pop("available_colours")
220         if gamestate.seeds > cost:
221             pos = pymunk.pygame_util.from_pygame(
222                 ev.pos, pygame.display.get_surface())
223             # Bail if we're too close to an existing light, obstacle or turnip
224             if check_space_for_light(self._space, pos, max_distance=25):
225                 return
226             gamestate.seeds -= cost
227             cfg["position"] = pos
228             cfg["colours"] = colours
229             gamestate.station["lights"].append(cfg)
230             self._lights.add_light(cfg)
231
232     def event(self, ev, gamestate):
233         if self._ending:
234             return
235         if self._game_over_text:
236             if ev.type in (pgl.KEYDOWN, pgl.MOUSEBUTTONDOWN):
237                 self._ending = True
238                 from .menu import MenuScene
239                 SceneChangeEvent.post(scene=MenuScene())
240         if ev.type == pgl.KEYDOWN:
241             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
242                 self._ending = True
243                 from .menu import MenuScene
244                 SceneChangeEvent.post(scene=MenuScene())
245             elif ev.key == pgl.K_e:
246                 self.end_day(gamestate)
247             elif ev.key == pgl.K_SPACE and DEBUG:
248                 self._paused = not self._paused
249         elif ev.type == pgl.MOUSEBUTTONDOWN:
250             if ev.button == 1:
251                 # Check tools
252                 for tool in self._tools:
253                     if tool.pressed(ev):
254                         self._color = None
255                         if tool.name == 'reset tool':
256                             self._unset_cursor()
257                             self._tool = None
258                             self._clear_light_toolbar()
259                         elif tool.name == 'start night':
260                             self.end_day(gamestate)
261                         elif tool.name == 'exit':
262                             self._ending = True
263                             from .menu import MenuScene
264                             SceneChangeEvent.post(scene=MenuScene())
265                         else:
266                             self._tool = tool
267                             if self._tool.name == 'seed':
268                                 self._set_cursor(
269                                     'seed', transform=Alpha(alpha=172))
270                                 self._clear_light_toolbar()
271                             elif self._tool.name == 'light':
272                                 self._unset_cursor()
273                                 self._draw_light_toolbar(
274                                     self._tool.light_config, 100)
275                         return
276                 # Check light toolbar
277                 for light_tool in self._light_toolbar:
278                     if light_tool.pressed(ev):
279                         fitting_image = light_fitting_by_type(
280                             self._tool.light_config["type"])
281                         self._set_cursor(
282                             fitting_image[:-4],  # strip .png
283                             transform=ColourWedges(colours=light_tool.colours))
284                         # colour=COLOURS[0] + (172,)))
285                         self._light_colors = light_tool.colours
286                         return
287                 if self._tool:
288                     if self._tool.name == "seed":
289                         self._place_seed(gamestate, ev)
290                     elif self._tool.name == "light" and self._light_colors:
291                         self._place_light(
292                             gamestate, self._tool.light_config,
293                             self._light_colors, ev)
294                 else:
295                     # Not tool, so check lights
296                     self._lights.toggle_nearest(ev.pos, surfpos=True)
297             elif ev.button == 3:
298                 light = self._lights.nearest(ev.pos, surfpos=True,
299                                              max_distance=20.0)
300                 if light:
301                     # Start drag to rotate light
302                     self._dragging = light
303                 elif self._tool:
304                     # Unset tool
305                     self._tool = None
306                     self._clear_light_toolbar()
307                     self._unset_cursor()
308         elif ev.type == pgl.MOUSEMOTION:
309             if self._dragging:
310                 # Calculate angle between current position and mouse pos
311                 self._update_light_angle(ev.pos, gamestate)
312         elif ev.type == pgl.MOUSEBUTTONUP:
313             self._dragging = None
314
315     @debug_timer("day.tick")
316     def tick(self, gamestate):
317         if not self._paused:
318             self._lights.tick()