8dd9c7b84add10af9ffbb1187ef1baa8d22f98a1
[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, seed_cost
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             cost = seed_cost(light_config, len(colours))
174             
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             font = loader.load_font(FONTS["sans"], size=12)
180             tool_cost = font.render("%d" % cost, True, (0, 0, 0))
181             light_tool._img.blit(tool_cost, (16, 12), None)
182             
183             light_tool.colours = colours
184             light_tool.cost = cost
185             self._light_toolbar.append(light_tool)
186             x += 40
187
188     def _clear_light_toolbar(self):
189         self._light_toolbar = []
190
191     def _place_seed(self, gamestate, ev):
192         if gamestate.seeds > 0:
193             # plant seed
194             # We don't want top-left to equal the mouse position,
195             # since that looks weird, but we don't want to center
196             # the turnip under the mouse either, since that
197             # causes issues as well, so we compromise
198             pos = (ev.pos[0] - 6, ev.pos[1] - 6)
199             try:
200                 turnip = Turnip(age=0, pos=pos, space=self._space)
201                 self._turnips.append(turnip)
202                 gamestate.seeds -= 1
203             except TurnipInvalidPosition:
204                 sound.play_sound("beep_kind.ogg")
205
206     def _update_light_angle(self, pos, gamestate):
207         # Update the angle of the given light
208         pos = pymunk.pygame_util.to_pygame(pos, pygame.display.get_surface())
209         distance = pos - self._dragging.position
210         angle = math.atan2(distance[1], distance[0])
211         # Set light angle to this position
212         self._dragging.ray_manager.direction = math.degrees(angle)
213         self._dragging.ray_manager.update_shapes()
214         # Hackily update gamestate with new angle
215         for light_cfg in gamestate.station["lights"]:
216             light_pos = pymunk.Vec2d(light_cfg["position"])
217             if light_pos.get_dist_sqrd(self._dragging.position) < 5.0:
218                 light_cfg["direction"] = math.degrees(angle)
219                 break
220
221     def _place_light(self, gamestate, cfg, cost, colours, ev):
222         cfg = cfg.copy()
223         cfg.pop("available_colours")
224         if gamestate.seeds > cost:
225             pos = pymunk.pygame_util.from_pygame(
226                 ev.pos, pygame.display.get_surface())
227             # Bail if we're too close to an existing light, obstacle or turnip
228             if check_space_for_light(self._space, pos, max_distance=25):
229                 sound.play_sound("beep_kind.ogg")
230                 return
231             gamestate.seeds -= cost
232             cfg["position"] = pos
233             cfg["colours"] = colours
234             gamestate.station["lights"].append(cfg)
235             self._lights.add_light(cfg)
236
237     def _remove_light(self, ev):
238         light = self._lights.nearest(ev.pos, surfpos=True, max_distance=25.0)
239         if light:
240             self._lights.remove_light(light)
241
242     def event(self, ev, gamestate):
243         if self._ending:
244             return
245         if self._game_over_text:
246             if ev.type in (pgl.KEYDOWN, pgl.MOUSEBUTTONDOWN):
247                 self._ending = True
248                 from .menu import MenuScene
249                 SceneChangeEvent.post(scene=MenuScene())
250         if ev.type == pgl.KEYDOWN:
251             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
252                 self._ending = True
253                 from .menu import MenuScene
254                 SceneChangeEvent.post(scene=MenuScene())
255             elif ev.key == pgl.K_e:
256                 self.end_day(gamestate)
257             elif ev.key == pgl.K_SPACE and DEBUG:
258                 self._paused = not self._paused
259         elif ev.type == pgl.MOUSEBUTTONDOWN:
260             if ev.button == 1:
261                 # Check tools
262                 for tool in self._tools:
263                     if tool.pressed(ev):
264                         self._color = None
265                         if tool.name == 'reset tool':
266                             self._unset_cursor()
267                             self._tool = None
268                             self._clear_light_toolbar()
269                         elif tool.name == 'start night':
270                             self.end_day(gamestate)
271                         elif tool.name == 'exit':
272                             self._ending = True
273                             from .menu import MenuScene
274                             SceneChangeEvent.post(scene=MenuScene())
275                         else:
276                             self._tool = tool
277                             if self._tool.name == 'seed':
278                                 self._set_cursor(
279                                     'seed', transform=Alpha(alpha=172))
280                                 self._clear_light_toolbar()
281                             elif self._tool.name == 'remove light':
282                                 self._set_cursor(
283                                     'remove', transform=Alpha(alpha=172))
284                                 self._clear_light_toolbar()
285                             elif self._tool.name == 'light':
286                                 self._unset_cursor()
287                                 self._draw_light_toolbar(
288                                     self._tool.light_config, 100)
289                         return
290                 # Check light toolbar
291                 for light_tool in self._light_toolbar:
292                     if light_tool.pressed(ev):
293                         fitting_image = light_fitting_by_type(
294                             self._tool.light_config["type"])
295                         self._set_cursor(
296                             fitting_image[:-4],  # strip .png
297                             transform=ColourWedges(colours=light_tool.colours))
298                         # colour=COLOURS[0] + (172,)))
299                         self._light_colors = light_tool.colours
300                         self._light_cost = light_tool.cost
301                         return
302                 if self._tool:
303                     if self._tool.name == "seed":
304                         self._place_seed(gamestate, ev)
305                     elif self._tool.name == "remove light":
306                         self._remove_light(ev)
307                     elif self._tool.name == "light" and self._light_colors:
308                         self._place_light(
309                             gamestate, self._tool.light_config,
310                             self._light_cost, self._light_colors, ev)
311                 else:
312                     # Not tool, so check lights
313                     self._lights.toggle_nearest(ev.pos, surfpos=True)
314             elif ev.button == 3:
315                 light = self._lights.nearest(ev.pos, surfpos=True,
316                                              max_distance=20.0)
317                 if light:
318                     # Start drag to rotate light
319                     self._dragging = light
320                 elif self._tool:
321                     # Unset tool
322                     self._tool = None
323                     self._clear_light_toolbar()
324                     self._unset_cursor()
325         elif ev.type == pgl.MOUSEMOTION:
326             if self._dragging:
327                 # Calculate angle between current position and mouse pos
328                 self._update_light_angle(ev.pos, gamestate)
329         elif ev.type == pgl.MOUSEBUTTONUP:
330             self._dragging = None
331
332     @debug_timer("day.tick")
333     def tick(self, gamestate):
334         if not self._paused:
335             self._lights.tick()