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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use geom::{Duration, Time};
use map_gui::ID;
use map_model::IntersectionID;
use widgetry::{
    Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, RewriteColor, State,
    StyledButtons, 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);
// TODO Avoid hack entirely, or tune appearance
const METER_HACK: f64 = -15.0;

pub struct FixTrafficSignals {
    top_center: Panel,
    meter: Panel,
    time: Time,
    done_at: Option<Time>,
    mode: GameplayMode,
}

impl FixTrafficSignals {
    pub fn new(ctx: &mut EventCtx, app: &App) -> Box<dyn GameplayState> {
        Box::new(FixTrafficSignals {
            top_center: Panel::empty(ctx),
            meter: make_meter(ctx, app, None),
            time: Time::START_OF_DAY,
            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,
        controls: &mut SandboxControls,
        _: &mut Actions,
    ) -> Option<Transition> {
        self.meter.align_below(
            ctx,
            &controls.agent_meter.as_ref().unwrap().panel,
            METER_HACK,
        );

        // 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();

            if let Some((i, t)) = app
                .primary
                .sim_cb
                .as_mut()
                .unwrap()
                .downcast_mut::<FindDelayedIntersections>()
                .unwrap()
                .currently_delayed
                .get(0)
                .cloned()
            {
                let dt = app.primary.sim.time() - t;
                self.meter = make_meter(ctx, app, Some((i, dt)));
                if dt >= THRESHOLD {
                    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(i)).unwrap(),
                            Some(10.0),
                            None,
                            &mut app.primary,
                        )),
                    ]));
                }
            } else {
                self.meter = make_meter(ctx, app, None);
            }
            self.meter.align_below(
                ctx,
                &controls.agent_meter.as_ref().unwrap().panel,
                METER_HACK,
            );

            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_center.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(Line("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.draw(ctx);
                    return Some(Transition::Push(FYI::new(ctx, contents, app.cs.panel_bg)));
                }
                "try again" => {
                    return Some(Transition::Replace(SandboxMode::simple_new(
                        ctx,
                        app,
                        self.mode.clone(),
                    )));
                }
                _ => unreachable!(),
            },
            _ => {}
        }
        match self.meter.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "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."),
                        ])
                        .draw(ctx),
                        app.cs.panel_bg,
                    )));
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        None
    }

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

    fn recreate_panels(&mut self, ctx: &mut EventCtx, _app: &App) {
        if let Some(time) = self.done_at {
            self.top_center = Panel::new(Widget::col(vec![
                challenge_header(ctx, "Traffic signal survivor"),
                Widget::row(vec![
                    Line(format!("Delay exceeded {} at {}", THRESHOLD, time))
                        .fg(Color::RED)
                        .draw(ctx)
                        .centered_vert(),
                    ctx.style()
                        .btn_outline_light_text("try again")
                        .build_def(ctx),
                ]),
            ]))
            .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
            .build(ctx);
        } else {
            self.top_center = Panel::new(Widget::col(vec![
                challenge_header(ctx, "Traffic signal survivor"),
                Widget::row(vec![
                    Line(format!(
                        "Keep delay at all intersections under {}",
                        THRESHOLD
                    ))
                    .draw(ctx),
                    ctx.style()
                        .btn_plain_light_icon_text("system/assets/tools/lightbulb.svg", "Hint")
                        .build_widget(ctx, "hint")
                        .align_right(),
                ]),
            ]))
            .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
            .build(ctx);
        }

        // self.meter is recreated as time changes anyway
    }

    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 make_meter(ctx: &mut EventCtx, app: &App, worst: Option<(IntersectionID, Duration)>) -> Panel {
    Panel::new(Widget::col(vec![
        Widget::horiz_separator(ctx, 0.2),
        if let Some((_, delay)) = 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")
                    }),
                ])
                .draw(ctx),
                ctx.style()
                    .btn_plain_light_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_light_icon("system/assets/tools/info.svg")
                        .build_widget(ctx, "explain score")
                } else {
                    Widget::nothing()
                },
                Text::from_all(vec![Line("Worst delay: "), Line("none!").secondary()]).draw(ctx),
                Widget::draw_svg_transform(
                    ctx,
                    "system/assets/tools/location.svg",
                    RewriteColor::ChangeAlpha(0.5),
                )
                .align_right(),
            ])
        },
    ]))
    .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
    .build(ctx)
}

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 {
    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),
        ])
        .draw(ctx)
        .margin_below(30),
        Widget::custom_row(vec![
            Widget::col(vec![
                Line("Time").fg(Color::BLACK).draw(ctx),
                Widget::draw_svg_transform(
                    ctx,
                    "system/assets/tools/time.svg",
                    RewriteColor::ChangeAll(Color::BLACK),
                ),
                Line("24 hours").fg(Color::BLACK).draw(ctx),
            ]),
            Widget::col(vec![
                Line("Goal").fg(Color::BLACK).draw(ctx),
                Widget::draw_svg_transform(
                    ctx,
                    "system/assets/tools/location.svg",
                    RewriteColor::ChangeAll(Color::BLACK),
                ),
                Text::from_multiline(vec![
                    Line("Keep delay at all intersections").fg(Color::BLACK),
                    Line(format!("under {}", THRESHOLD)).fg(Color::BLACK),
                ])
                .draw(ctx),
            ]),
            Widget::col(vec![
                Line("Score").fg(Color::BLACK).draw(ctx),
                Widget::draw_svg_transform(
                    ctx,
                    "system/assets/tools/star.svg",
                    RewriteColor::ChangeAll(Color::BLACK),
                ),
                Line("How long you survive").fg(Color::BLACK).draw(ctx),
            ]),
        ])
        .evenly_spaced(),
    ])
}