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