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