Render cost
[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             font = loader.load_font(FONTS["sans"], size=12)
107             tool_cost = font.render("%d" % light_config["cost"], True, (0, 0, 0))
108             tool._img.blit(tool_cost, (16, 12), None)
109             tool.light_config = light_config
110             tools.append(tool)
111             x += step
112
113         tools.append(ImageButton(
114             '32', 'remove.png', name='remove light', pos=(x, y)))
115         x += step
116
117         tools.append(ImageButton(
118             '32', 'default_cursor.png', name='reset tool', pos=(x, y)))
119
120         tools.append(ImageButton(
121             '32', 'night.png', name='start night',
122             pos=(SCREEN_SIZE[0] - 100, y)))
123         tools.append(ImageButton(
124             '32', 'exit.png', name='exit', pos=(SCREEN_SIZE[0] - 50, y)))
125         return tools
126
127     def exit(self, gamestate):
128         self._unset_cursor()
129
130     def end_day(self, gamestate):
131         if self._ending:
132             return
133         self._battery.apply_recharge()
134         gamestate.update_lights(self._lights)
135         turnip_data = [turnip.serialize() for turnip in self._turnips]
136         gamestate.turnips = turnip_data
137         self._ending = True
138         from .night import NightScene
139         SceneChangeEvent.post(scene=NightScene())
140
141     @property
142     def turnip_count(self):
143         return len(self._turnips)
144
145     @property
146     def power_usage(self):
147         power = self._lights.total_power_usage()
148         power = power / (FPS * NIGHT_HOURS_PER_TICK)
149         return int(round(power))
150
151     @debug_timer("day.render")
152     def render(self, surface, gamestate):
153         surface.blit(self._soil, (0, 0))
154
155         for turnip in self._turnips:
156             turnip.render(surface)
157         self._lights.render_light(surface)
158         self._obstacles.render(surface)
159         self._lights.render_fittings(surface)
160         self._infobar.render(surface, gamestate)
161         for tool in self._tools:
162             tool.render(surface)
163         for light_tool in self._light_toolbar:
164             light_tool.render(surface)
165         self._draw_cursor(surface)
166         if self._game_over_text:
167             for surf, pos in self._game_over_text:
168                 surface.blit(surf, pos)
169
170     def _draw_light_toolbar(self, light_config, x):
171         height = SCREEN_SIZE[1] - 80
172         self._light_toolbar = []
173         colour_combos = light_config["available_colours"]
174         for combo in colour_combos:
175             colours = combo.split("/")
176             light_fitting = light_fitting_by_type(light_config["type"])
177             light_tool = ImageButton(
178                 "32", light_fitting, transform=ColourWedges(colours=colours),
179                 pos=(x, height), name=combo)
180             light_tool.colours = colours
181             self._light_toolbar.append(light_tool)
182             x += 40
183
184     def _clear_light_toolbar(self):
185         self._light_toolbar = []
186
187     def _place_seed(self, gamestate, ev):
188         if gamestate.seeds > 0:
189             # plant seed
190             # We don't want top-left to equal the mouse position,
191             # since that looks weird, but we don't want to center
192             # the turnip under the mouse either, since that
193             # causes issues as well, so we compromise
194             pos = (ev.pos[0] - 18, ev.pos[1] - 18)
195             try:
196                 turnip = Turnip(age=0, pos=pos, space=self._space)
197                 self._turnips.append(turnip)
198                 gamestate.seeds -= 1
199             except TurnipInvalidPosition:
200                 sound.play_sound("beep_kind.ogg")
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                 sound.play_sound("beep_kind.ogg")
226                 return
227             gamestate.seeds -= cost
228             cfg["position"] = pos
229             cfg["colours"] = colours
230             gamestate.station["lights"].append(cfg)
231             self._lights.add_light(cfg)
232
233     def _remove_light(self, ev):
234         light = self._lights.nearest(ev.pos, surfpos=True, max_distance=25.0)
235         if light:
236             self._lights.remove_light(light)
237
238     def event(self, ev, gamestate):
239         if self._ending:
240             return
241         if self._game_over_text:
242             if ev.type in (pgl.KEYDOWN, pgl.MOUSEBUTTONDOWN):
243                 self._ending = True
244                 from .menu import MenuScene
245                 SceneChangeEvent.post(scene=MenuScene())
246         if ev.type == pgl.KEYDOWN:
247             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
248                 self._ending = True
249                 from .menu import MenuScene
250                 SceneChangeEvent.post(scene=MenuScene())
251             elif ev.key == pgl.K_e:
252                 self.end_day(gamestate)
253             elif ev.key == pgl.K_SPACE and DEBUG:
254                 self._paused = not self._paused
255         elif ev.type == pgl.MOUSEBUTTONDOWN:
256             if ev.button == 1:
257                 # Check tools
258                 for tool in self._tools:
259                     if tool.pressed(ev):
260                         self._color = None
261                         if tool.name == 'reset tool':
262                             self._unset_cursor()
263                             self._tool = None
264                             self._clear_light_toolbar()
265                         elif tool.name == 'start night':
266                             self.end_day(gamestate)
267                         elif tool.name == 'exit':
268                             self._ending = True
269                             from .menu import MenuScene
270                             SceneChangeEvent.post(scene=MenuScene())
271                         else:
272                             self._tool = tool
273                             if self._tool.name == 'seed':
274                                 self._set_cursor(
275                                     'seed', transform=Alpha(alpha=172))
276                                 self._clear_light_toolbar()
277                             elif self._tool.name == 'remove light':
278                                 self._set_cursor(
279                                     'remove', transform=Alpha(alpha=172))
280                                 self._clear_light_toolbar()
281                             elif self._tool.name == 'light':
282                                 self._unset_cursor()
283                                 self._draw_light_toolbar(
284                                     self._tool.light_config, 100)
285                         return
286                 # Check light toolbar
287                 for light_tool in self._light_toolbar:
288                     if light_tool.pressed(ev):
289                         fitting_image = light_fitting_by_type(
290                             self._tool.light_config["type"])
291                         self._set_cursor(
292                             fitting_image[:-4],  # strip .png
293                             transform=ColourWedges(colours=light_tool.colours))
294                         # colour=COLOURS[0] + (172,)))
295                         self._light_colors = light_tool.colours
296                         return
297                 if self._tool:
298                     if self._tool.name == "seed":
299                         self._place_seed(gamestate, ev)
300                     elif self._tool.name == "remove light":
301                         self._remove_light(ev)
302                     elif self._tool.name == "light" and self._light_colors:
303                         self._place_light(
304                             gamestate, self._tool.light_config,
305                             self._light_colors, ev)
306                 else:
307                     # Not tool, so check lights
308                     self._lights.toggle_nearest(ev.pos, surfpos=True)
309             elif ev.button == 3:
310                 light = self._lights.nearest(ev.pos, surfpos=True,
311                                              max_distance=20.0)
312                 if light:
313                     # Start drag to rotate light
314                     self._dragging = light
315                 elif self._tool:
316                     # Unset tool
317                     self._tool = None
318                     self._clear_light_toolbar()
319                     self._unset_cursor()
320         elif ev.type == pgl.MOUSEMOTION:
321             if self._dragging:
322                 # Calculate angle between current position and mouse pos
323                 self._update_light_angle(ev.pos, gamestate)
324         elif ev.type == pgl.MOUSEBUTTONUP:
325             self._dragging = None
326
327     @debug_timer("day.tick")
328     def tick(self, gamestate):
329         if not self._paused:
330             self._lights.tick()