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