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