Merge branch 'master' of ctpug.org.za:tabakrolletjie
[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._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
85         x, y, step = 50, SCREEN_SIZE[1] - 40, 50
86
87         tools.append(ImageButton('32', 'seed.png', name='seed', pos=(x, y)))
88         x += step
89
90         for light_config in gamestate.station["available_lights"]:
91             tool = ImageButton(
92                 '32', '%s.png' % light_config["type"], name='light',
93                 pos=(x, y))
94             tool.light_config = light_config
95             tools.append(tool)
96             x += step
97
98         tools.append(ImageButton(
99             '32', 'default_cursor.png', name='reset tool', pos=(x, y)))
100
101         tools.append(ImageButton(
102             '32', 'night.png', name='start night',
103             pos=(SCREEN_SIZE[0] - 100, y)))
104         tools.append(ImageButton(
105             '32', 'exit.png', name='exit', pos=(SCREEN_SIZE[0] - 50, y)))
106         return tools
107
108     def exit(self, gamestate):
109         self._unset_cursor()
110         gamestate.seeds = self._seeds
111         gamestate.harvested = self._harvested
112         turnip_data = [turnip.serialize() for turnip in self._turnips]
113         gamestate.turnips = turnip_data
114
115     def end_day(self, gamestate):
116         self._battery.apply_recharge()
117         from .night import NightScene
118         SceneChangeEvent.post(scene=NightScene())
119
120     @debug_timer("day.render")
121     def render(self, surface, gamestate):
122         surface.blit(self._soil, (0, 0))
123
124         for turnip in self._turnips:
125             turnip.render(surface)
126         self._lights.render_light(surface)
127         self._obstacles.render(surface)
128         self._lights.render_fittings(surface)
129         surface.blit(self._toolbar, (120, 10), None)
130         for tool in self._tools:
131             tool.render(surface)
132         for light_tool in self._light_toolbar:
133             light_tool.render(surface)
134         self._draw_cursor(surface)
135         if self._game_over_text:
136             for surf, pos in self._game_over_text:
137                 surface.blit(surf, pos)
138
139     def _draw_light_toolbar(self, light_config, x):
140         height = SCREEN_SIZE[1] - 80
141         self._light_toolbar = []
142         colour_combos = light_config["available_colours"]
143         for combo in colour_combos:
144             colours = combo.split("/")
145             light_fitting = light_fitting_by_type(light_config["type"])
146             light_tool = ImageButton(
147                 "32", light_fitting, transform=ColourWedges(colours=colours),
148                 pos=(x, height), name=combo)
149             light_tool.colours = colours
150             self._light_toolbar.append(light_tool)
151             x += 40
152
153     def _clear_light_toolbar(self):
154         self._light_toolbar = []
155
156     def _place_seed(self, gamestate, ev):
157         if self._seeds > 0:
158             # plant seed
159             # We don't want top-left to equal the mouse position,
160             # since that looks weird, but we don't want to center
161             # the turnip under the mouse either, since that
162             # causes issues as well, so we compromise
163             pos = (ev.pos[0] - 8, ev.pos[1] - 8)
164             try:
165                 turnip = Turnip(age=0, pos=pos, space=self._space)
166                 self._turnips.append(turnip)
167                 self._seeds -= 1
168                 self._update_toolbar(gamestate)
169             except TurnipInvalidPosition:
170                 # TODO: Add error sound or something
171                 pass
172
173     def _update_light_angle(self, pos, gamestate):
174         # Update the angle of the given light
175         pos = pymunk.pygame_util.to_pygame(pos, pygame.display.get_surface())
176         distance = pos - self._dragging.position
177         angle = math.atan2(distance[1], distance[0])
178         # Set light angle to this position
179         self._dragging.ray_manager.direction = math.degrees(angle)
180         # Hackily update gamestate with new angle
181         for light_cfg in gamestate.station["lights"]:
182             light_pos = pymunk.Vec2d(light_cfg["position"])
183             if light_pos.get_dist_sqrd(self._dragging.position) < 5.0:
184                 light_cfg["direction"] = math.degrees(angle)
185                 break
186
187     def _place_light(self, gamestate, cfg, colours, ev):
188         cfg = cfg.copy()
189         cost = cfg.pop("cost")
190         cfg.pop("available_colours")
191         if self._seeds > cost:
192             pos = pymunk.pygame_util.from_pygame(
193                 ev.pos, pygame.display.get_surface())
194             # Bail if we're too close to an existing light
195             if self._lights.nearest(pos, max_distance=25):
196                 return
197             self._seeds -= cost
198             self._update_toolbar(gamestate)
199             cfg["position"] = pos
200             cfg["colours"] = colours
201             gamestate.station["lights"].append(cfg)
202             self._lights.add_light(cfg)
203
204     def event(self, ev, gamestate):
205         if self._game_over_text:
206             if ev.type in (pgl.KEYDOWN, pgl.MOUSEBUTTONDOWN):
207                 from .menu import MenuScene
208                 SceneChangeEvent.post(scene=MenuScene())
209         if ev.type == pgl.KEYDOWN:
210             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
211                 from .menu import MenuScene
212                 SceneChangeEvent.post(scene=MenuScene())
213             elif ev.key == pgl.K_e:
214                 self.end_day(gamestate)
215             elif ev.key == pgl.K_SPACE and DEBUG:
216                 self._paused = not self._paused
217         elif ev.type == pgl.MOUSEBUTTONDOWN:
218             if ev.button == 1:
219                 # Check tools
220                 for tool in self._tools:
221                     if tool.pressed(ev):
222                         self._color = None
223                         if tool.name == 'reset tool':
224                             self._unset_cursor()
225                             self._tool = None
226                             self._clear_light_toolbar()
227                         elif tool.name == 'start night':
228                             self.end_day(gamestate)
229                         elif tool.name == 'exit':
230                             from .menu import MenuScene
231                             SceneChangeEvent.post(scene=MenuScene())
232                         else:
233                             self._tool = tool
234                             if self._tool.name == 'seed':
235                                 self._set_cursor(
236                                     'seed', transform=Alpha(alpha=172))
237                                 self._clear_light_toolbar()
238                             elif self._tool.name == 'light':
239                                 self._unset_cursor()
240                                 self._draw_light_toolbar(
241                                     self._tool.light_config, 100)
242                         return
243                 # Check light toolbar
244                 for light_tool in self._light_toolbar:
245                     if light_tool.pressed(ev):
246                         fitting_image = light_fitting_by_type(
247                             self._tool.light_config["type"])
248                         self._set_cursor(
249                             fitting_image[:-4],  # strip .png
250                             transform=ColourWedges(colours=light_tool.colours))
251                         # colour=COLOURS[0] + (172,)))
252                         self._light_colors = light_tool.colours
253                         return
254                 if self._tool:
255                     if self._tool.name == "seed":
256                         self._place_seed(gamestate, ev)
257                     elif self._tool.name == "light" and self._light_colors:
258                         self._place_light(
259                             gamestate, self._tool.light_config,
260                             self._light_colors, ev)
261                 else:
262                     # Not tool, so check lights
263                     self._lights.toggle_nearest(ev.pos, surfpos=True)
264             elif ev.button == 3:
265                 light = self._lights.nearest(ev.pos, surfpos=True,
266                                              max_distance=20.0)
267                 if light:
268                     # Start drag to rotate light
269                     self._dragging = light
270                 elif self._tool:
271                     # Unset tool
272                     self._tool = None
273                     self._clear_light_toolbar()
274                     self._unset_cursor()
275         elif ev.type == pgl.MOUSEMOTION:
276             if self._dragging:
277                 # Calculate angle between current position and mouse pos
278                 self._update_light_angle(ev.pos, gamestate)
279         elif ev.type == pgl.MOUSEBUTTONUP:
280             self._dragging = None
281
282     @debug_timer("day.tick")
283     def tick(self, gamestate):
284         if not self._paused:
285             self._lights.tick()
286
287     def _update_toolbar(self, gamestate):
288         text = ("Day: %d: Turnip Stocks: Seeds: %d. Planted: %d. "
289                 "Harvested: %d. Destroyed: %d" %
290                 (gamestate.days, self._seeds, len(self._turnips),
291                  self._harvested, gamestate.eaten))
292         self._toolbar = self._toolbar_font.render(text, True, (255, 255, 255))