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