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