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