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