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