fbsim-core 1.0.0-beta.2

A library for american football simulation
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#![doc = include_str!("../../../docs/game/play/context.md")]
#[cfg(feature = "rocket_okapi")]
use rocket_okapi::okapi::schemars;
#[cfg(feature = "rocket_okapi")]
use rocket_okapi::okapi::schemars::JsonSchema;
use serde::{Serialize, Deserialize};

use crate::game::context::GameContext;

/// # `PlayContext` struct
///
/// A `PlayContext` represents a play scenario
#[cfg_attr(feature = "rocket_okapi", derive(JsonSchema))]
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Default, Serialize, Deserialize)]
pub struct PlayContext {
    quarter: u32,
    half_seconds: u32,
    down: u32,
    distance: u32,
    yard_line: u32,
    score_diff: i32,
    off_timeouts: u32,
    def_timeouts: u32,
    clock_running: bool
}

impl From<&GameContext> for PlayContext {
    /// Initialize a PlayContext from a borrowed GameContext
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// ```
    fn from(item: &GameContext) -> PlayContext {
        // Determine score diff and timeouts based on possession
        let score_diff: i32 = if item.home_possession() {
            item.home_score() as i32 - item.away_score() as i32
        } else {
            item.away_score() as i32 - item.home_score() as i32
        };
        let off_timeouts: u32 = if item.home_possession() {
            item.home_timeouts()
        } else {
            item.away_timeouts()
        };
        let def_timeouts: u32 = if item.home_possession() {
            item.away_timeouts()
        } else {
            item.home_timeouts()
        };

        // Determine yard line based on possession and direction
        let yard_line: u32 = if item.home_possession() ^ item.home_positive_direction() {
            u32::try_from(100_i32 - item.yard_line() as i32).unwrap_or_default()
        } else {
            item.yard_line()
        };

        // Construct the play context
        PlayContext{
            quarter: item.quarter(),
            half_seconds: item.half_seconds(),
            down: item.down(),
            distance: item.distance(),
            yard_line,
            score_diff,
            off_timeouts,
            def_timeouts,
            clock_running: item.clock_running()
        }
    }
}

impl PlayContext {
    /// Whether the offense is losing
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let losing = play_context.losing();
    /// assert!(!losing);
    /// ```
    pub fn losing(&self) -> bool {
        self.score_diff < 0
    }

    /// Whether the score is tied
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let tied = play_context.tied();
    /// assert!(tied);
    /// ```
    pub fn tied(&self) -> bool {
        self.score_diff == 0
    }

    /// Whether to go for 2 after a touchdown
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let two_point_conversion = play_context.two_point_conversion();
    /// assert!(!two_point_conversion);
    /// ```
    pub fn two_point_conversion(&self) -> bool {
        self.quarter == 4 && (
            matches!(
                self.score_diff,
                25 | 22 | 19 | 5 | 4 | 1 | -2 | -5 | -10 | -12 | -13
            ) || self.score_diff < -15
        )
    }

    /// Whether the clock is running
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let clock_running = play_context.clock_running();
    /// assert!(!clock_running);
    /// ```
    pub fn clock_running(&self) -> bool {
        self.clock_running
    }

    /// Gets the current down
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let down = play_context.down();
    /// assert!(down == 0);
    /// ```
    pub fn down(&self) -> u32 {
        self.down
    }

    /// Gets the current distance
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let distance = play_context.distance();
    /// assert!(distance == 10);
    /// ```
    pub fn distance(&self) -> u32 {
        self.distance
    }

    /// Gets the current yard line
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let yard_line = play_context.yard_line();
    /// assert!(yard_line == 35);
    /// ```
    pub fn yard_line(&self) -> u32 {
        self.yard_line
    }

    /// Gets the number of timeouts the offense has
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let offense_timeouts = play_context.offense_timeouts();
    /// assert!(offense_timeouts == 3);
    /// ```
    pub fn offense_timeouts(&self) -> u32 {
        self.off_timeouts
    }

    /// Gets the number of timeouts the defense has
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let defense_timeouts = play_context.defense_timeouts();
    /// assert!(defense_timeouts == 3);
    /// ```
    pub fn defense_timeouts(&self) -> u32 {
        self.def_timeouts
    }

    /// Gets the current quarter
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let quarter = play_context.quarter();
    /// assert!(quarter == 1);
    /// ```
    pub fn quarter(&self) -> u32 {
        self.quarter
    }

    /// Whether this is a drain-clock scenario for the offense
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let drain_clock = play_context.drain_clock();
    /// assert!(!drain_clock);
    /// ```
    pub fn drain_clock(&self) -> bool {
        if self.score_diff <= 0 {
            return false
        }
        let scores_up_by: f32 = self.score_diff as f32 / 8_f32;
        let drain_threshold_sig: i32 = (scores_up_by * 4_f32 * 60_f32) as i32;
        let drain_threshold: u32 = u32::try_from(drain_threshold_sig).unwrap_or_default();
        if self.quarter >= 4 && self.half_seconds < drain_threshold {
            return true
        }
        false
    }

    /// Whether this is an up-tempo scenario for the offense
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let up_tempo = play_context.up_tempo();
    /// assert!(!up_tempo);
    /// ```
    pub fn up_tempo(&self) -> bool {
        (self.quarter == 2 || self.quarter >= 4) && self.half_seconds <= 180 &&
        self.score_diff < 0 && self.score_diff >= -17
    }

    /// Whether this is a critical down scenario
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let critical_down = play_context.critical_down();
    /// assert!(!critical_down);
    /// ```
    pub fn critical_down(&self) -> bool {
        self.down == 3 && self.half_seconds <= 180 &&
        self.score_diff < 9 && self.score_diff > -9
    }

    /// Whether this is a conserve-clock scenario for the offense
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let conserve_clock = play_context.offense_conserve_clock();
    /// assert!(!conserve_clock);
    /// ```
    pub fn offense_conserve_clock(&self) -> bool {
        (self.quarter == 2 || self.quarter >= 4) && self.half_seconds <= 180 &&
        self.score_diff < 0 && self.score_diff > -18
    }

    /// Whether this is a conserve-clock scenario for the defense
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let conserve_clock = play_context.defense_conserve_clock();
    /// assert!(!conserve_clock);
    /// ```
    pub fn defense_conserve_clock(&self) -> bool {
        self.quarter >= 4 && self.half_seconds <= 180 &&
        self.score_diff > 0 && self.score_diff < 18
    }

    /// Whether the clock could run out if left running
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let last_play_clock_running = play_context.last_play_clock_running();
    /// assert!(!last_play_clock_running);
    /// ```
    pub fn last_play_clock_running(&self) -> bool {
        self.half_seconds < 40
    }

    /// Whether this is the last play
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let last_play = play_context.last_play();
    /// assert!(!last_play);
    /// ```
    pub fn last_play(&self) -> bool {
        self.half_seconds < 6
    }

    /// Whether the offense needs a touchdown on the last play
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let last_play_need_td = play_context.last_play_need_td();
    /// assert!(!last_play_need_td);
    /// ```
    pub fn last_play_need_td(&self) -> bool {
        self.score_diff < -3
    }

    /// Whether the kicking team needs to kick an onside kick
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let onside_kick = play_context.onside_kick();
    /// assert!(!onside_kick);
    /// ```
    pub fn onside_kick(&self) -> bool {
        self.score_diff < 0 && self.quarter >= 4 && self.must_score()
    }

    /// Whether the offense can kneel to end the game
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let can_kneel = play_context.can_kneel();
    /// assert!(!can_kneel);
    /// ```
    pub fn can_kneel(&self) -> bool {
        let downs_remaining = 4 - self.down;
        let runoff_seconds = 42 * downs_remaining.checked_sub(self.def_timeouts).unwrap_or_default();
        runoff_seconds >= self.half_seconds
    }

    /// Whether this is a must-score scenario for 4th-down playcalling
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let must_score = play_context.must_score();
    /// assert!(!must_score);
    /// ```
    pub fn must_score(&self) -> bool {
        if self.score_diff >= 0 {
            return false
        }
        let timeout_drive_time = (42 * (3 - self.off_timeouts)) + 8;
        if self.half_seconds <= timeout_drive_time {
            return true
        }
        let non_timeout_drive_time = (42 * 3) + 8;
        let timeout_drives_remaining: u32 = 1;
        let non_timeout_drive_time_remaining = self.half_seconds.checked_sub(timeout_drive_time).unwrap_or_default();
        let non_timeout_drives_remaining = (
            non_timeout_drive_time_remaining as f32 / non_timeout_drive_time as f32
        ).ceil() as u32;
        let scores_needed = (self.score_diff as f32 / 8_f32).round().abs() as u32;
        let drives_remaining = timeout_drives_remaining + non_timeout_drives_remaining;
        drives_remaining <= scores_needed
    }

    /// Whether this is a go for it on 4th scenario
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let can_go_for_it = play_context.can_go_for_it();
    /// assert!(!can_go_for_it);
    /// ```
    pub fn can_go_for_it(&self) -> bool {
        self.distance <= 4 && (
            self.yard_line >= 80 ||
            (self.yard_line >= 40 && self.yard_line <= 60)
        )
    }

    /// Whether the offense is in field goal range
    ///
    /// ### Example
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    /// 
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// let in_field_goal_range = play_context.in_field_goal_range();
    /// assert!(!in_field_goal_range);
    /// ```
    pub fn in_field_goal_range(&self) -> bool {
        self.yard_line >= 45
    }
}

impl std::fmt::Display for PlayContext {
    /// Format a `PlayContext` as a string.
    ///
    /// ### Example
    ///
    /// ```
    /// use fbsim_core::game::context::GameContext;
    /// use fbsim_core::game::play::context::PlayContext;
    ///
    /// // Initialize a play context and display it
    /// let game_context = GameContext::new();
    /// let play_context = PlayContext::from(&game_context);
    /// println!("{}", play_context);
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Format the clock
        let clock_total = if self.half_seconds < 900 || 
            (self.half_seconds == 900 && self.quarter.is_multiple_of(2) && self.quarter <= 4) {
            self.half_seconds
        } else {
            self.half_seconds - 900
        };
        let clock_mins = clock_total / 60;
        let clock_secs = clock_total - (clock_mins * 60);
        let clock_secs_str = if clock_secs < 10 {
            format!("0{}", clock_secs)
        } else {
            format!("{}", clock_secs)
        };
        let clock_str = format!("{}:{}", clock_mins, &clock_secs_str);

        // Format the quarter
        let quarter_str = if self.quarter <= 4 {
            format!("{}Q", self.quarter)
        } else {
            let num_ot = self.quarter - 4;
            format!("{}OT", num_ot)
        };

        // Format the down & distance
        let down_suf = match self.down {
            1 => "st",
            2 => "nd",
            3 => "rd",
            _ => "th"
        };
        let down_dist_str = if self.yard_line + self.distance >= 100 {
            format!("{}{} & goal", self.down, down_suf)
        } else {
            format!("{}{} & {}", self.down, down_suf, self.distance)
        };

        // Format the yard line
        let (yard, side_of_field) = if self.yard_line < 50 {
            (self.yard_line, "OWN")
        } else {
            (100 - self.yard_line, "OPP")
        };
        let yard_str = format!("{} {}", side_of_field, yard);

        // Format the play context
        let context_str = format!(
            "[{} {}] {} at {}",
            clock_str,
            quarter_str,
            down_dist_str,
            yard_str
        );
        f.write_str(&context_str)
    }
}