1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
use geom::{Duration, Time};
use map_gui::ID;
use map_model::IntersectionID;
use widgetry::{
    Color, EventCtx, GfxCtx, HorizontalAlignment, Image, Key, Line, Outcome, Panel, RewriteColor,
    State, Text, VerticalAlignment, Widget,
};

use crate::app::Transition;
use crate::app::{App, FindDelayedIntersections};
use crate::challenges::cutscene::{CutsceneBuilder, FYI};
use crate::challenges::HighScore;
use crate::common::Warping;
use crate::edit::EditMode;
use crate::sandbox::gameplay::{challenge_header, FinalScore, GameplayMode, GameplayState};
use crate::sandbox::{Actions, SandboxControls, SandboxMode};

const THRESHOLD: Duration = Duration::const_seconds(20.0 * 60.0);

pub struct FixTrafficSignals {
    top_right: Panel,
    time: Time,
    worst: Option<(IntersectionID, Duration)>,
    done_at: Option<Time>,
    mode: GameplayMode,
}

impl FixTrafficSignals {
    pub fn new(ctx: &mut EventCtx) -> Box<dyn GameplayState> {
        Box::new(FixTrafficSignals {
            top_right: Panel::empty(ctx),
            time: Time::START_OF_DAY,
            worst: None,
            done_at: None,
            mode: GameplayMode::FixTrafficSignals,
        })
    }

    pub fn cutscene_pt1(ctx: &mut EventCtx, _: &App, _: &GameplayMode) -> Box<dyn State<App>> {
        CutsceneBuilder::new("Traffic signal survivor")
            .boss("I hope you've had your coffee. There's a huge mess downtown.")
            .player("Did two buses get tangled together again?")
            .boss("Worse. SCOOT along Mercer is going haywire.")
            .player("SCOOT?")
            .boss(
                "You know, Split Cycle Offset Optimization Technique, the traffic signal \
                 coordination system? Did you sleep through college or what?",
            )
            .boss(
                "It's offline. All the traffic signals look like they've been reset to industry \
                 defaults.",
            )
            .player("Uh oh. Too much scooter traffic overwhelm it? Eh? EHH?")
            .boss("...")
            .boss("You know, not every problem you will face in life is caused by a pun.")
            .boss(
                "Most, in fact, will be caused by me ruining your life because you won't take \
                 your job seriously.",
            )
            .player("Sorry, boss.")
            .extra(
                "parents.svg.gz",
                0.6,
                "Hi, er, we're calling from Lower Queen Anne. What's going on?!",
            )
            .extra(
                "parents.svg.gz",
                0.6,
                "We just missed a VERY important appointment. Nobody's moving an inch!",
            )
            .boss(
                "Oh no... reports are coming in, ALL of the traffic signals downtown are screwed \
                 up!",
            )
            .boss(
                "You need to go fix all of them. But listen, you haven't got much time. Focus on \
                 the worst problems first.",
            )
            .player("Sigh... it's going to be a long day.")
            .build(ctx, Box::new(cutscene_pt1_task))
    }
}

impl GameplayState for FixTrafficSignals {
    fn event(
        &mut self,
        ctx: &mut EventCtx,
        app: &mut App,
        _: &mut SandboxControls,
        _: &mut Actions,
    ) -> Option<Transition> {
        // Normally we just do this once at the beginning, but because there are other paths to
        // reseting (like jump-to-time), it's safest just to do this.
        if app.primary.sim_cb.is_none() {
            app.primary.sim_cb = Some(Box::new(FindDelayedIntersections {
                halt_limit: THRESHOLD,
                report_limit: Duration::minutes(1),
                currently_delayed: Vec::new(),
            }));
            app.primary.sim.set_periodic_callback(Duration::minutes(1));
        }

        if self.time != app.primary.sim.time() && self.done_at.is_none() {
            self.time = app.primary.sim.time();

            self.worst = None;
            if let Some((i, t)) = app
                .primary
                .sim_cb
                .as_mut()
                .unwrap()
                .downcast_mut::<FindDelayedIntersections>()
                .unwrap()
                .currently_delayed
                .get(0)
                .cloned()
            {
                self.worst = Some((i, app.primary.sim.time() - t));
            }

            if self
                .worst
                .map(|(_, delay)| delay >= THRESHOLD)
                .unwrap_or(false)
            {
                self.done_at = Some(app.primary.sim.time());
                self.recreate_panels(ctx, app);

                return Some(Transition::Multi(vec![
                    Transition::Push(final_score(ctx, app, self.mode.clone(), true)),
                    Transition::Push(Warping::new(
                        ctx,
                        app.primary
                            .canonical_point(ID::Intersection(self.worst.unwrap().0))
                            .unwrap(),
                        Some(10.0),
                        None,
                        &mut app.primary,
                    )),
                ]));
            } else {
                self.recreate_panels(ctx, app);
            }

            if app.primary.sim.is_done() {
                self.done_at = Some(app.primary.sim.time());
                // TODO The score is up to 1 min (report_limit) off.
                return Some(Transition::Push(final_score(
                    ctx,
                    app,
                    self.mode.clone(),
                    false,
                )));
            }
        }

        match self.top_right.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "edit map" => {
                    return Some(Transition::Push(EditMode::new(ctx, app, self.mode.clone())));
                }
                "instructions" => {
                    let contents = cutscene_pt1_task(ctx);
                    return Some(Transition::Push(FYI::new(ctx, contents, Color::WHITE)));
                }
                "hint" => {
                    // TODO Multiple hints. Point to layers.
                    let mut txt = Text::from("Hint");
                    txt.add_line("");
                    txt.add_appended(vec![
                        Line("Press "),
                        Key::L.txt(ctx),
                        Line(" to open layers. Try "),
                        Key::D.txt(ctx),
                        Line("elay or worst traffic "),
                        Key::J.txt(ctx),
                        Line("ams"),
                    ]);
                    let contents = txt.into_widget(ctx);
                    return Some(Transition::Push(FYI::new(ctx, contents, app.cs.panel_bg)));
                }
                "try again" => {
                    return Some(Transition::Replace(SandboxMode::simple_new(
                        app,
                        self.mode.clone(),
                    )));
                }
                "go to slowest intersection" => {
                    let i = app
                        .primary
                        .sim_cb
                        .as_ref()
                        .unwrap()
                        .downcast_ref::<FindDelayedIntersections>()
                        .unwrap()
                        .currently_delayed[0]
                        .0;
                    return Some(Transition::Push(Warping::new(
                        ctx,
                        app.primary.canonical_point(ID::Intersection(i)).unwrap(),
                        Some(10.0),
                        None,
                        &mut app.primary,
                    )));
                }
                "explain score" => {
                    // TODO Adjust wording
                    return Some(Transition::Push(FYI::new(
                        ctx,
                        Text::from_multiline(vec![
                            Line("You changed some traffic signals in the middle of the day."),
                            Line(
                                "First see if you can survive for a full day, making changes \
                                 along the way.",
                            ),
                            Line("Then you should check if your changes work from midnight."),
                        ])
                        .into_widget(ctx),
                        app.cs.panel_bg,
                    )));
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        None
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        self.top_right.draw(g);
    }

    fn recreate_panels(&mut self, ctx: &mut EventCtx, app: &App) {
        if let Some(time) = self.done_at {
            self.top_right = Panel::new(Widget::col(vec![
                challenge_header(ctx, "Traffic signal survivor"),
                Widget::row(vec![
                    Line(format!("Delay exceeded {} at {}", THRESHOLD, time))
                        .fg(Color::RED)
                        .into_widget(ctx)
                        .centered_vert(),
                    ctx.style().btn_outline.text("try again").build_def(ctx),
                ]),
            ]))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx);
        } else {
            let meter = if let Some((_, delay)) = self.worst {
                Widget::row(vec![
                    Text::from_all(vec![
                        Line("Worst delay: "),
                        Line(delay.to_string(&app.opts.units)).fg(
                            if delay < Duration::minutes(5) {
                                Color::hex("#F9EC51")
                            } else if delay < Duration::minutes(15) {
                                Color::hex("#EE702E")
                            } else {
                                Color::hex("#EB3223")
                            },
                        ),
                    ])
                    .into_widget(ctx),
                    ctx.style()
                        .btn_plain
                        .icon("system/assets/tools/location.svg")
                        .build_widget(ctx, "go to slowest intersection")
                        .align_right(),
                ])
            } else {
                Widget::row(vec![
                    if app.primary.dirty_from_edits {
                        ctx.style()
                            .btn_plain
                            .icon("system/assets/tools/info.svg")
                            .build_widget(ctx, "explain score")
                    } else {
                        Widget::nothing()
                    },
                    Text::from_all(vec![Line("Worst delay: "), Line("none!").secondary()])
                        .into_widget(ctx),
                    Image::from_path("system/assets/tools/location.svg")
                        .color(RewriteColor::ChangeAlpha(0.5))
                        .into_widget(ctx)
                        .align_right(),
                ])
            };

            self.top_right = Panel::new(Widget::col(vec![
                challenge_header(ctx, "Traffic signal survivor"),
                Widget::row(vec![
                    Line(format!(
                        "Keep delay at all intersections under {}",
                        THRESHOLD
                    ))
                    .into_widget(ctx),
                    ctx.style()
                        .btn_plain
                        .icon_text("system/assets/tools/lightbulb.svg", "Hint")
                        .build_widget(ctx, "hint")
                        .align_right(),
                ]),
                meter,
            ]))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx);
        }
    }

    fn on_destroy(&self, app: &mut App) {
        assert!(app.primary.sim_cb.is_some());
        app.primary.sim_cb = None;
        app.primary.sim.unset_periodic_callback();
    }
}

fn final_score(
    ctx: &mut EventCtx,
    app: &mut App,
    mode: GameplayMode,
    failed: bool,
) -> Box<dyn State<App>> {
    let score = app.primary.sim.time() - Time::START_OF_DAY;
    HighScore {
        goal: format!(
            "make it {} without delay exceeding {}",
            app.primary.sim.get_end_of_day() - Time::START_OF_DAY,
            THRESHOLD
        ),
        score,
        edits_name: app.primary.map.get_edits().edits_name.clone(),
    }
    .record(app, mode.clone());

    let msg = if failed {
        format!(
            "You only made it {} before the traffic signals caused a jam. Lame!",
            score
        )
    } else {
        "Wow, you managed to fix the signals. Great job!".to_string()
    };
    FinalScore::new(ctx, app, msg, mode, None)
}

// TODO Can we automatically transform text and SVG colors?
fn cutscene_pt1_task(ctx: &mut EventCtx) -> Widget {
    let icon_builder = Image::empty().color(Color::BLACK).dims(50.0);
    Widget::custom_col(vec![
        Text::from_multiline(vec![
            Line(format!(
                "Don't let anyone be delayed by one traffic signal more than {}!",
                THRESHOLD
            ))
            .fg(Color::BLACK),
            Line("Survive as long as possible through 24 hours of a busy weekday.")
                .fg(Color::BLACK),
        ])
        .into_widget(ctx)
        .margin_below(30),
        Widget::custom_row(vec![
            Widget::col(vec![
                Line("Time").fg(Color::BLACK).into_widget(ctx),
                icon_builder
                    .clone()
                    .source_path("system/assets/tools/time.svg")
                    .into_widget(ctx),
                Line("24 hours").fg(Color::BLACK).into_widget(ctx),
            ]),
            Widget::col(vec![
                Line("Goal").fg(Color::BLACK).into_widget(ctx),
                icon_builder
                    .clone()
                    .source_path("system/assets/tools/location.svg")
                    .into_widget(ctx),
                Text::from_multiline(vec![
                    Line("Keep delay at all intersections").fg(Color::BLACK),
                    Line(format!("under {}", THRESHOLD)).fg(Color::BLACK),
                ])
                .into_widget(ctx),
            ]),
            Widget::col(vec![
                Line("Score").fg(Color::BLACK).into_widget(ctx),
                icon_builder
                    .source_path("system/assets/tools/star.svg")
                    .into_widget(ctx),
                Line("How long you survive")
                    .fg(Color::BLACK)
                    .into_widget(ctx),
            ]),
        ])
        .evenly_spaced(),
    ])
}