ferravex_play/
rounds.rs

1//! Authoritative tactical round/economy rules. The host supplies validated movement
2//! and hit results; this module validates teams, phase, money, bomb possession,
3//! interaction distance, alive state, and uninterrupted plant/defuse durations.
4//!
5//! Menus can read [`TacticalMatch::summary`] without consuming events or advancing
6//! time. Continue authoritative fixed ticks while a local menu is open; call
7//! [`TacticalMatch::reset`] only when the authority starts a fresh match.
8use std::collections::VecDeque;
9
10pub type PlayerId = u16;
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Team {
13    Attack,
14    Defend,
15}
16impl Team {
17    fn index(self) -> usize {
18        match self {
19            Self::Attack => 0,
20            Self::Defend => 1,
21        }
22    }
23    fn other(self) -> Self {
24        match self {
25            Self::Attack => Self::Defend,
26            Self::Defend => Self::Attack,
27        }
28    }
29}
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Weapon {
32    Pistol,
33    Rifle,
34    Sniper,
35}
36impl Weapon {
37    pub fn price(self) -> u32 {
38        match self {
39            Self::Pistol => 200,
40            Self::Rifle => 2700,
41            Self::Sniper => 4750,
42        }
43    }
44}
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Phase {
47    Buy,
48    Live,
49    Planted,
50    PostRound,
51    Finished,
52}
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum WinReason {
55    Forfeit,
56    Elimination,
57    TimeExpired,
58    Explosion,
59    Defused,
60}
61/// The most recently accepted round result, retained independently of events.
62///
63/// See [`TacticalMatch::summary`] for an example. A forfeit records the current
64/// round and ends the match immediately, including during buy or intermission.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct RoundOutcome {
67    /// One-based round in which the result was accepted.
68    pub round: u32,
69    pub winner: Team,
70    pub reason: WinReason,
71}
72/// An allocation-free snapshot for round HUDs and menus.
73///
74/// Created by [`TacticalMatch::summary`]; reading it never drains feedback events
75/// or changes the authoritative phase. Team arrays use attack, then defend order.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct RoundSummary {
78    pub round: u32,
79    pub phase: Phase,
80    pub score: [u16; 2],
81    /// Time to the current phase's deadline, or zero when finished.
82    /// An earlier plant/defuse completion can change the phase first.
83    pub remaining_seconds: f32,
84    /// Remaining phase seconds rounded up for display; `None` when finished.
85    pub countdown_seconds: Option<u32>,
86    /// Latest result, retained through subsequent rounds until replaced or reset.
87    /// `None` before the first result of a fresh match.
88    pub last_outcome: Option<RoundOutcome>,
89    /// Set only after entering [`Phase::Finished`], including by forfeit.
90    /// A match-clinching intermission still has no match winner here.
91    pub match_winner: Option<Team>,
92}
93#[derive(Clone, Copy, Debug, PartialEq)]
94pub enum Bomb {
95    Carried(PlayerId),
96    Dropped([f32; 3]),
97    Planted { site: usize, position: [f32; 3] },
98}
99#[derive(Clone, Copy, Debug)]
100pub struct Site {
101    pub center: [f32; 3],
102    pub radius: f32,
103}
104#[derive(Clone, Copy, Debug)]
105pub struct PlayerSetup {
106    pub id: PlayerId,
107    pub team: Team,
108    pub spawn: [f32; 3],
109}
110#[derive(Clone, Debug)]
111pub struct Player {
112    pub id: PlayerId,
113    pub team: Team,
114    pub position: [f32; 3],
115    pub health: u16,
116    pub money: u32,
117    pub weapon: Weapon,
118    pub armor: u16,
119    pub defuse_kit: bool,
120    spawn: [f32; 3],
121}
122impl Player {
123    pub fn alive(&self) -> bool {
124        self.health > 0
125    }
126}
127#[derive(Clone, Debug)]
128pub struct Config {
129    pub buy_seconds: f32,
130    pub round_seconds: f32,
131    pub bomb_seconds: f32,
132    pub plant_seconds: f32,
133    pub defuse_seconds: f32,
134    pub kit_defuse_seconds: f32,
135    pub intermission_seconds: f32,
136    pub rounds_to_win: u16,
137    pub starting_money: u32,
138    pub sites: Vec<Site>,
139}
140impl Default for Config {
141    fn default() -> Self {
142        Self {
143            buy_seconds: 10.0,
144            round_seconds: 115.0,
145            bomb_seconds: 40.0,
146            plant_seconds: 3.0,
147            defuse_seconds: 10.0,
148            kit_defuse_seconds: 5.0,
149            intermission_seconds: 3.0,
150            rounds_to_win: 13,
151            starting_money: 800,
152            sites: vec![
153                Site {
154                    center: [10.0, 0.0, 10.0],
155                    radius: 4.0,
156                },
157                Site {
158                    center: [-10.0, 0.0, 10.0],
159                    radius: 4.0,
160                },
161            ],
162        }
163    }
164}
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum Action {
167    BuyWeapon(Weapon),
168    BuyArmor,
169    BuyDefuseKit,
170    Plant(usize),
171    Defuse,
172    Cancel,
173    DropBomb,
174    PickUpBomb,
175}
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub enum RuleError {
178    InvalidConfig,
179    InvalidRoster,
180    UnknownPlayer,
181    WrongPhase,
182    Dead,
183    WrongTeam,
184    InsufficientFunds,
185    AlreadyOwned,
186    BombUnavailable,
187    OutOfRange,
188    Busy,
189    InvalidInput,
190}
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum Event {
193    RoundStarted(u32),
194    Killed {
195        attacker: PlayerId,
196        victim: PlayerId,
197    },
198    Planted {
199        player: PlayerId,
200        site: usize,
201    },
202    RoundWon {
203        team: Team,
204        reason: WinReason,
205    },
206    MatchWon(Team),
207}
208#[derive(Clone, Copy)]
209enum Interaction {
210    Plant(usize),
211    Defuse,
212}
213#[derive(Clone, Copy)]
214struct Channel {
215    player: PlayerId,
216    action: Interaction,
217    elapsed: f32,
218    required: f32,
219    origin: [f32; 3],
220}
221
222pub struct TacticalMatch {
223    config: Config,
224    players: Vec<Player>,
225    phase: Phase,
226    remaining: f32,
227    bomb: Bomb,
228    channel: Option<Channel>,
229    score: [u16; 2],
230    loss_streak: [u8; 2],
231    round: u32,
232    last_outcome: Option<RoundOutcome>,
233    events: VecDeque<Event>,
234}
235impl TacticalMatch {
236    pub fn new(config: Config, roster: Vec<PlayerSetup>) -> Result<Self, RuleError> {
237        if ![
238            config.buy_seconds,
239            config.round_seconds,
240            config.bomb_seconds,
241            config.plant_seconds,
242            config.defuse_seconds,
243            config.kit_defuse_seconds,
244            config.intermission_seconds,
245        ]
246        .into_iter()
247        .all(|n| n.is_finite() && n > 0.0 && n <= 3600.0)
248            || config.rounds_to_win == 0
249            || config.starting_money > 16000
250            || config.sites.is_empty()
251            || config.sites.len() > 32
252            || config
253                .sites
254                .iter()
255                .any(|site| !finite(site.center) || !site.radius.is_finite() || site.radius <= 0.0)
256        {
257            return Err(RuleError::InvalidConfig);
258        }
259        if roster.len() < 2
260            || roster.len() > 64
261            || !roster.iter().any(|p| p.team == Team::Attack)
262            || !roster.iter().any(|p| p.team == Team::Defend)
263            || roster
264                .iter()
265                .enumerate()
266                .any(|(i, p)| !finite(p.spawn) || roster[..i].iter().any(|old| old.id == p.id))
267        {
268            return Err(RuleError::InvalidRoster);
269        }
270        let carrier = roster
271            .iter()
272            .find(|p| p.team == Team::Attack)
273            .expect("validated attackers")
274            .id;
275        let players = roster
276            .into_iter()
277            .map(|p| Player {
278                id: p.id,
279                team: p.team,
280                position: p.spawn,
281                spawn: p.spawn,
282                health: 100,
283                money: config.starting_money,
284                weapon: Weapon::Pistol,
285                armor: 0,
286                defuse_kit: false,
287            })
288            .collect();
289        let remaining = config.buy_seconds;
290        let mut game = Self {
291            config,
292            players,
293            phase: Phase::Buy,
294            remaining,
295            bomb: Bomb::Carried(carrier),
296            channel: None,
297            score: [0; 2],
298            loss_streak: [0; 2],
299            round: 1,
300            last_outcome: None,
301            events: VecDeque::with_capacity(128),
302        };
303        game.start_round();
304        Ok(game)
305    }
306    /// Start a fresh match with the same validated config, roster and spawns.
307    ///
308    /// Restores round one/buy time, starting money, health, pistol loadouts and
309    /// initial bomb ownership. Clears scores, loss streaks, interactions, outcome
310    /// history and queued events, then queues exactly one [`Event::RoundStarted`].
311    /// Repeated calls produce the same state and reuse existing roster/event
312    /// storage. Disconnected players are restored too; use a new match if the
313    /// roster has changed.
314    ///
315    /// This is an authority operation, not a local menu pause. The caller owns
316    /// resetting its clock, pending input, feedback and external game entities.
317    ///
318    /// ```
319    /// use ferravex_play::rounds::{Config, Event, Phase, PlayerSetup, TacticalMatch, Team};
320    /// let mut game = TacticalMatch::new(Config::default(), vec![
321    ///     PlayerSetup { id: 1, team: Team::Attack, spawn: [0.0; 3] },
322    ///     PlayerSetup { id: 2, team: Team::Defend, spawn: [1.0, 0.0, 0.0] },
323    /// ]).unwrap();
324    /// game.forfeit(Team::Attack);
325    /// game.reset();
326    /// game.reset(); // No stale win events or duplicate start notifications.
327    /// assert_eq!(game.summary().phase, Phase::Buy);
328    /// assert_eq!(game.summary().last_outcome, None);
329    /// assert_eq!(game.pop_event(), Some(Event::RoundStarted(1)));
330    /// assert_eq!(game.pop_event(), None);
331    /// ```
332    pub fn reset(&mut self) {
333        self.score = [0; 2];
334        self.loss_streak = [0; 2];
335        self.round = 1;
336        self.last_outcome = None;
337        self.events.clear();
338        for player in &mut self.players {
339            player.money = self.config.starting_money;
340            player.weapon = Weapon::Pistol;
341            player.armor = 0;
342            player.defuse_kit = false;
343        }
344        self.start_round();
345    }
346    /// Read round, countdown and outcome information without consuming events.
347    ///
348    /// The result is a detached value. Countdown rounding is presentation only;
349    /// phase transitions still occur exclusively through the rules' mutations.
350    /// The latest outcome survives event draining and the start of another round.
351    ///
352    /// ```
353    /// use ferravex_play::rounds::{
354    ///     Config, Phase, PlayerSetup, RoundOutcome, TacticalMatch, Team, WinReason,
355    /// };
356    /// let mut game = TacticalMatch::new(Config::default(), vec![
357    ///     PlayerSetup { id: 1, team: Team::Attack, spawn: [0.0; 3] },
358    ///     PlayerSetup { id: 2, team: Team::Defend, spawn: [1.0, 0.0, 0.0] },
359    /// ]).unwrap();
360    /// game.tick(0.25).unwrap();
361    /// let menu = game.summary();
362    /// assert_eq!(menu.remaining_seconds, 9.75);
363    /// assert_eq!(menu.countdown_seconds, Some(10));
364    /// game.forfeit(Team::Attack);
365    /// while game.pop_event().is_some() {}
366    /// let result = game.summary();
367    /// assert_eq!(result.phase, Phase::Finished);
368    /// assert_eq!(result.countdown_seconds, None);
369    /// assert_eq!(result.match_winner, Some(Team::Defend));
370    /// assert_eq!(result.last_outcome, Some(RoundOutcome {
371    ///     round: 1, winner: Team::Defend, reason: WinReason::Forfeit,
372    /// }));
373    /// assert_eq!(menu.phase, Phase::Buy); // Earlier snapshots remain unchanged.
374    /// ```
375    pub fn summary(&self) -> RoundSummary {
376        let (countdown_seconds, match_winner) = match self.phase {
377            Phase::Finished => (None, self.last_outcome.map(|outcome| outcome.winner)),
378            _ => (Some(self.remaining.ceil() as u32), None),
379        };
380        RoundSummary {
381            round: self.round,
382            phase: self.phase,
383            score: self.score,
384            remaining_seconds: self.remaining,
385            countdown_seconds,
386            last_outcome: self.last_outcome,
387            match_winner,
388        }
389    }
390    /// Remove a disconnected player's live contribution without inventing a killer.
391    /// Stable roster slots remain dead until a later authority roster reset.
392    pub fn disconnect(&mut self, id: PlayerId) -> Result<(), RuleError> {
393        let i = self.index(id)?;
394        self.players[i].health = 0;
395        if self.bomb == Bomb::Carried(id) {
396            self.bomb = Bomb::Dropped(self.players[i].position);
397        }
398        if self.channel.is_some_and(|c| c.player == id) {
399            self.channel = None;
400        }
401        if matches!(self.phase, Phase::Live | Phase::Planted) {
402            self.check_elimination();
403        }
404        Ok(())
405    }
406    /// Authority-only disconnect forfeit. A client action cannot invoke this.
407    /// Ends the match immediately so disconnected roster slots cannot resurrect
408    /// on the next round and prevent elimination indefinitely.
409    pub fn forfeit(&mut self, team: Team) {
410        if self.phase == Phase::Finished {
411            return;
412        }
413        for player in &mut self.players {
414            if player.team == team {
415                player.health = 0;
416            }
417        }
418        if let Bomb::Carried(id) = self.bomb
419            && let Some(player) = self.player(id)
420            && !player.alive()
421        {
422            self.bomb = Bomb::Dropped(player.position);
423        }
424        let winner = team.other();
425        self.channel = None;
426        self.score[winner.index()] = self.config.rounds_to_win;
427        self.phase = Phase::Finished;
428        self.remaining = 0.;
429        self.last_outcome = Some(RoundOutcome {
430            round: self.round,
431            winner,
432            reason: WinReason::Forfeit,
433        });
434        self.emit(Event::RoundWon {
435            team: winner,
436            reason: WinReason::Forfeit,
437        });
438        self.emit(Event::MatchWon(winner));
439    }
440    pub fn phase(&self) -> Phase {
441        self.phase
442    }
443    pub fn remaining(&self) -> f32 {
444        self.remaining
445    }
446    pub fn round(&self) -> u32 {
447        self.round
448    }
449    pub fn score(&self) -> [u16; 2] {
450        self.score
451    }
452    pub fn bomb(&self) -> Bomb {
453        self.bomb
454    }
455    pub fn players(&self) -> &[Player] {
456        &self.players
457    }
458    pub fn player(&self, id: PlayerId) -> Option<&Player> {
459        self.players.iter().find(|p| p.id == id)
460    }
461    pub fn interaction_progress(&self) -> Option<(PlayerId, f32)> {
462        self.channel
463            .map(|c| (c.player, (c.elapsed / c.required).clamp(0.0, 1.0)))
464    }
465    pub fn pop_event(&mut self) -> Option<Event> {
466        self.events.pop_front()
467    }
468    /// Integrate movement on the authoritative host, then provide its accepted position.
469    /// Moving >15 cm from interaction origin interrupts plant/defuse.
470    pub fn set_position(&mut self, id: PlayerId, position: [f32; 3]) -> Result<(), RuleError> {
471        if !finite(position) {
472            return Err(RuleError::InvalidInput);
473        }
474        let index = self.index(id)?;
475        if !self.players[index].alive() {
476            return Err(RuleError::Dead);
477        }
478        self.players[index].position = position;
479        if self
480            .channel
481            .is_some_and(|c| c.player == id && distance(c.origin, position) > 0.15)
482        {
483            self.channel = None;
484        }
485        Ok(())
486    }
487    pub fn act(&mut self, id: PlayerId, action: Action) -> Result<(), RuleError> {
488        let index = self.index(id)?;
489        let player = &self.players[index];
490        if !player.alive() {
491            return Err(RuleError::Dead);
492        }
493        match action {
494            Action::BuyWeapon(weapon) => {
495                if self.phase != Phase::Buy {
496                    return Err(RuleError::WrongPhase);
497                }
498                if player.weapon == weapon {
499                    return Err(RuleError::AlreadyOwned);
500                }
501                self.spend(index, weapon.price())?;
502                self.players[index].weapon = weapon;
503            }
504            Action::BuyArmor => {
505                if self.phase != Phase::Buy {
506                    return Err(RuleError::WrongPhase);
507                }
508                if player.armor == 100 {
509                    return Err(RuleError::AlreadyOwned);
510                }
511                self.spend(index, 650)?;
512                self.players[index].armor = 100;
513            }
514            Action::BuyDefuseKit => {
515                if self.phase != Phase::Buy {
516                    return Err(RuleError::WrongPhase);
517                }
518                if player.team != Team::Defend {
519                    return Err(RuleError::WrongTeam);
520                }
521                if player.defuse_kit {
522                    return Err(RuleError::AlreadyOwned);
523                }
524                self.spend(index, 400)?;
525                self.players[index].defuse_kit = true;
526            }
527            Action::Cancel => {
528                if self.channel.is_some_and(|c| c.player == id) {
529                    self.channel = None;
530                }
531            }
532            Action::Plant(site_index) => {
533                if self.phase != Phase::Live {
534                    return Err(RuleError::WrongPhase);
535                }
536                if player.team != Team::Attack {
537                    return Err(RuleError::WrongTeam);
538                }
539                if self.bomb != Bomb::Carried(id) {
540                    return Err(RuleError::BombUnavailable);
541                }
542                let site = self
543                    .config
544                    .sites
545                    .get(site_index)
546                    .ok_or(RuleError::OutOfRange)?;
547                if distance(site.center, player.position) > site.radius {
548                    return Err(RuleError::OutOfRange);
549                }
550                if self.channel.is_some() {
551                    return Err(RuleError::Busy);
552                }
553                self.channel = Some(Channel {
554                    player: id,
555                    action: Interaction::Plant(site_index),
556                    elapsed: 0.0,
557                    required: self.config.plant_seconds,
558                    origin: player.position,
559                });
560            }
561            Action::Defuse => {
562                if self.phase != Phase::Planted {
563                    return Err(RuleError::WrongPhase);
564                }
565                if player.team != Team::Defend {
566                    return Err(RuleError::WrongTeam);
567                }
568                let Bomb::Planted { position, .. } = self.bomb else {
569                    return Err(RuleError::BombUnavailable);
570                };
571                if distance(position, player.position) > 2.5 {
572                    return Err(RuleError::OutOfRange);
573                }
574                if self.channel.is_some() {
575                    return Err(RuleError::Busy);
576                }
577                self.channel = Some(Channel {
578                    player: id,
579                    action: Interaction::Defuse,
580                    elapsed: 0.0,
581                    required: if player.defuse_kit {
582                        self.config.kit_defuse_seconds
583                    } else {
584                        self.config.defuse_seconds
585                    },
586                    origin: player.position,
587                });
588            }
589            Action::DropBomb => {
590                if self.phase != Phase::Live {
591                    return Err(RuleError::WrongPhase);
592                }
593                if self.bomb != Bomb::Carried(id) {
594                    return Err(RuleError::BombUnavailable);
595                }
596                self.bomb = Bomb::Dropped(player.position);
597                self.channel = None;
598            }
599            Action::PickUpBomb => {
600                if self.phase != Phase::Live {
601                    return Err(RuleError::WrongPhase);
602                }
603                if player.team != Team::Attack {
604                    return Err(RuleError::WrongTeam);
605                }
606                let Bomb::Dropped(position) = self.bomb else {
607                    return Err(RuleError::BombUnavailable);
608                };
609                if distance(player.position, position) > 1.5 {
610                    return Err(RuleError::OutOfRange);
611                }
612                self.bomb = Bomb::Carried(id);
613            }
614        }
615        Ok(())
616    }
617    /// Apply a server-confirmed hit. Clients must never supply unvalidated hit results.
618    pub fn damage(
619        &mut self,
620        attacker: PlayerId,
621        victim: PlayerId,
622        amount: u16,
623    ) -> Result<(), RuleError> {
624        if !matches!(self.phase, Phase::Live | Phase::Planted) {
625            return Err(RuleError::WrongPhase);
626        }
627        let a = self.index(attacker)?;
628        let v = self.index(victim)?;
629        if !self.players[a].alive() || !self.players[v].alive() {
630            return Err(RuleError::Dead);
631        }
632        if self.players[a].team == self.players[v].team {
633            return Err(RuleError::WrongTeam);
634        }
635        let absorbed = self.players[v].armor.min(amount / 2);
636        self.players[v].armor -= absorbed;
637        self.players[v].health = self.players[v].health.saturating_sub(amount - absorbed);
638        if !self.players[v].alive() {
639            self.players[a].money = (self.players[a].money + 300).min(16000);
640            if self.bomb == Bomb::Carried(victim) {
641                self.bomb = Bomb::Dropped(self.players[v].position);
642            }
643            if self.channel.is_some_and(|c| c.player == victim) {
644                self.channel = None;
645            }
646            self.emit(Event::Killed { attacker, victim });
647            self.check_elimination();
648        }
649        Ok(())
650    }
651    /// Splits elapsed time at every phase/interaction deadline. Large steps produce
652    /// the same rule transitions as small steps. Bomb expiry wins exact defuse ties.
653    /// Zero time and valid ticks after match completion are no-ops; invalid deltas
654    /// are rejected even after completion.
655    pub fn tick(&mut self, mut dt: f32) -> Result<(), RuleError> {
656        if !dt.is_finite() || !(0.0..=3600.0).contains(&dt) {
657            return Err(RuleError::InvalidInput);
658        }
659        while dt > 0.0 && self.phase != Phase::Finished {
660            let channel_left = self
661                .channel
662                .map_or(f32::INFINITY, |c| (c.required - c.elapsed).max(0.0));
663            let step = dt.min(self.remaining).min(channel_left);
664            self.remaining = (self.remaining - step).max(0.0);
665            if let Some(channel) = &mut self.channel {
666                channel.elapsed += step;
667            }
668            dt = (dt - step).max(0.0);
669            if self.phase == Phase::Planted && self.remaining <= 1e-6 {
670                self.finish_round(Team::Attack, WinReason::Explosion);
671                continue;
672            }
673            if self.channel.is_some_and(|c| c.elapsed + 1e-6 >= c.required) {
674                self.finish_channel();
675                continue;
676            }
677            if self.remaining <= 1e-6 {
678                match self.phase {
679                    Phase::Buy => {
680                        self.phase = Phase::Live;
681                        self.remaining = self.config.round_seconds;
682                    }
683                    Phase::Live => self.finish_round(Team::Defend, WinReason::TimeExpired),
684                    Phase::PostRound => self.next_round(),
685                    Phase::Planted | Phase::Finished => {
686                        unreachable!("handled before phase transitions")
687                    }
688                }
689            }
690        }
691        Ok(())
692    }
693    fn index(&self, id: PlayerId) -> Result<usize, RuleError> {
694        self.players
695            .iter()
696            .position(|p| p.id == id)
697            .ok_or(RuleError::UnknownPlayer)
698    }
699    fn spend(&mut self, index: usize, price: u32) -> Result<(), RuleError> {
700        let player = &mut self.players[index];
701        if player.money < price {
702            return Err(RuleError::InsufficientFunds);
703        }
704        player.money -= price;
705        Ok(())
706    }
707    fn finish_channel(&mut self) {
708        let channel = self.channel.take().expect("completed channel");
709        match channel.action {
710            Interaction::Plant(site) => {
711                let index = self.index(channel.player).expect("roster stable");
712                self.bomb = Bomb::Planted {
713                    site,
714                    position: channel.origin,
715                };
716                self.phase = Phase::Planted;
717                self.remaining = self.config.bomb_seconds;
718                self.players[index].money = (self.players[index].money + 300).min(16000);
719                self.emit(Event::Planted {
720                    player: channel.player,
721                    site,
722                });
723            }
724            Interaction::Defuse => self.finish_round(Team::Defend, WinReason::Defused),
725        }
726    }
727    fn check_elimination(&mut self) {
728        let attacks = self
729            .players
730            .iter()
731            .any(|p| p.team == Team::Attack && p.alive());
732        let defends = self
733            .players
734            .iter()
735            .any(|p| p.team == Team::Defend && p.alive());
736        if !defends {
737            self.finish_round(Team::Attack, WinReason::Elimination);
738        } else if !attacks && self.phase != Phase::Planted {
739            self.finish_round(Team::Defend, WinReason::Elimination);
740        }
741    }
742    fn finish_round(&mut self, winner: Team, reason: WinReason) {
743        if !matches!(self.phase, Phase::Live | Phase::Planted) {
744            return;
745        }
746        self.phase = Phase::PostRound;
747        self.remaining = self.config.intermission_seconds;
748        self.channel = None;
749        self.last_outcome = Some(RoundOutcome {
750            round: self.round,
751            winner,
752            reason,
753        });
754        self.score[winner.index()] += 1;
755        self.loss_streak[winner.index()] = 0;
756        let loser = winner.other();
757        self.loss_streak[loser.index()] = (self.loss_streak[loser.index()] + 1).min(5);
758        let loss_reward = 1400 + u32::from(self.loss_streak[loser.index()] - 1) * 500;
759        for player in &mut self.players {
760            player.money = (player.money
761                + if player.team == winner {
762                    3250
763                } else {
764                    loss_reward
765                })
766            .min(16000);
767        }
768        self.emit(Event::RoundWon {
769            team: winner,
770            reason,
771        });
772    }
773    fn next_round(&mut self) {
774        let winner = self.last_outcome.expect("post round has outcome").winner;
775        if self.score[winner.index()] >= self.config.rounds_to_win {
776            self.phase = Phase::Finished;
777            self.remaining = 0.0;
778            self.emit(Event::MatchWon(winner));
779            return;
780        }
781        self.round += 1;
782        self.start_round();
783    }
784    fn start_round(&mut self) {
785        self.phase = Phase::Buy;
786        self.remaining = self.config.buy_seconds;
787        self.channel = None;
788        for player in &mut self.players {
789            if !player.alive() {
790                player.weapon = Weapon::Pistol;
791                player.armor = 0;
792                player.defuse_kit = false;
793            }
794            player.health = 100;
795            player.position = player.spawn;
796        }
797        self.bomb = Bomb::Carried(
798            self.players
799                .iter()
800                .find(|p| p.team == Team::Attack)
801                .expect("roster has attackers")
802                .id,
803        );
804        self.emit(Event::RoundStarted(self.round));
805    }
806    fn emit(&mut self, event: Event) {
807        if self.events.len() == 128 {
808            self.events.pop_front();
809        }
810        self.events.push_back(event);
811    }
812}
813fn finite(v: [f32; 3]) -> bool {
814    v.into_iter().all(f32::is_finite)
815}
816fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
817    ((f64::from(a[0]) - f64::from(b[0])).powi(2)
818        + (f64::from(a[1]) - f64::from(b[1])).powi(2)
819        + (f64::from(a[2]) - f64::from(b[2])).powi(2))
820    .sqrt() as f32
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826    fn game() -> TacticalMatch {
827        TacticalMatch::new(
828            Config {
829                buy_seconds: 1.0,
830                round_seconds: 10.0,
831                bomb_seconds: 8.0,
832                plant_seconds: 2.0,
833                defuse_seconds: 4.0,
834                kit_defuse_seconds: 2.0,
835                intermission_seconds: 1.0,
836                rounds_to_win: 2,
837                starting_money: 4000,
838                sites: vec![Site {
839                    center: [0.0; 3],
840                    radius: 3.0,
841                }],
842            },
843            vec![
844                PlayerSetup {
845                    id: 1,
846                    team: Team::Attack,
847                    spawn: [0.0; 3],
848                },
849                PlayerSetup {
850                    id: 2,
851                    team: Team::Defend,
852                    spawn: [1.0, 0.0, 0.0],
853                },
854            ],
855        )
856        .unwrap()
857    }
858    #[test]
859    fn purchases_validate_team_phase_money_and_ownership() {
860        let mut g = game();
861        g.act(1, Action::BuyWeapon(Weapon::Rifle)).unwrap();
862        assert_eq!(g.player(1).unwrap().money, 1300);
863        assert_eq!(
864            g.act(1, Action::BuyWeapon(Weapon::Sniper)),
865            Err(RuleError::InsufficientFunds)
866        );
867        assert_eq!(g.act(1, Action::BuyDefuseKit), Err(RuleError::WrongTeam));
868        g.act(2, Action::BuyDefuseKit).unwrap();
869        assert_eq!(g.act(2, Action::BuyDefuseKit), Err(RuleError::AlreadyOwned));
870        g.tick(1.0).unwrap();
871        assert_eq!(g.act(1, Action::BuyArmor), Err(RuleError::WrongPhase));
872    }
873    #[test]
874    fn plant_defuse_requires_uninterrupted_distance_checked_channels() {
875        let mut g = game();
876        g.act(2, Action::BuyDefuseKit).unwrap();
877        g.tick(1.0).unwrap();
878        g.act(1, Action::Plant(0)).unwrap();
879        g.tick(1.0).unwrap();
880        g.set_position(1, [0.2, 0.0, 0.0]).unwrap();
881        assert!(g.interaction_progress().is_none());
882        g.act(1, Action::Plant(0)).unwrap();
883        g.tick(2.0).unwrap();
884        assert_eq!(g.phase(), Phase::Planted);
885        g.act(2, Action::Defuse).unwrap();
886        g.tick(2.0).unwrap();
887        assert_eq!(g.phase(), Phase::PostRound);
888        assert_eq!(g.score(), [0, 1]);
889        assert_eq!(g.player(1).unwrap().money, 5700); // plant bonus + first loss
890    }
891    #[test]
892    fn planted_bomb_survives_attacker_elimination_and_expires() {
893        let mut g = game();
894        g.tick(1.0).unwrap();
895        g.act(1, Action::Plant(0)).unwrap();
896        g.tick(2.0).unwrap();
897        g.damage(2, 1, 100).unwrap();
898        assert_eq!(g.phase(), Phase::Planted);
899        g.tick(8.0).unwrap();
900        assert_eq!(g.score(), [1, 0]);
901    }
902    #[test]
903    fn elimination_economy_respawn_and_match_end() {
904        let mut g = game();
905        g.tick(1.0).unwrap();
906        g.damage(1, 2, 100).unwrap();
907        assert_eq!(g.player(1).unwrap().money, 7550);
908        assert_eq!(g.player(2).unwrap().money, 5400);
909        g.tick(1.0).unwrap();
910        assert_eq!(g.round(), 2);
911        assert!(g.player(2).unwrap().alive());
912        g.tick(1.0).unwrap();
913        g.damage(1, 2, 100).unwrap();
914        g.tick(1.0).unwrap();
915        assert_eq!(g.phase(), Phase::Finished);
916        assert_eq!(g.score(), [2, 0]);
917        assert_eq!(g.player(2).unwrap().money, 7300); // escalating loss bonus
918    }
919    #[test]
920    fn time_partitioning_and_exact_defuse_deadline_are_defined() {
921        let mut a = game();
922        let mut b = game();
923        a.tick(12.0).unwrap();
924        for _ in 0..120 {
925            b.tick(0.1).unwrap();
926        }
927        assert_eq!(a.phase(), b.phase());
928        assert_eq!(a.score(), b.score());
929        assert_eq!(a.round(), b.round());
930        let mut g = game();
931        g.tick(1.0).unwrap();
932        g.act(1, Action::Plant(0)).unwrap();
933        g.tick(2.0).unwrap();
934        g.tick(4.0).unwrap();
935        g.act(2, Action::Defuse).unwrap();
936        g.tick(4.0).unwrap();
937        assert_eq!(g.score(), [1, 0]); // explosion wins exact tie
938    }
939    #[test]
940    fn dropped_bomb_rejects_defender_and_remote_pickup() {
941        let mut g = game();
942        g.tick(1.0).unwrap();
943        g.act(1, Action::DropBomb).unwrap();
944        assert_eq!(g.act(2, Action::PickUpBomb), Err(RuleError::WrongTeam));
945        g.set_position(1, [5.0, 0.0, 0.0]).unwrap();
946        assert_eq!(g.act(1, Action::PickUpBomb), Err(RuleError::OutOfRange));
947        g.set_position(1, [0.0; 3]).unwrap();
948        g.act(1, Action::PickUpBomb).unwrap();
949        assert_eq!(g.bomb(), Bomb::Carried(1));
950    }
951
952    #[test]
953    fn summary_rounds_countdown_up_without_consuming_events_or_tracking_later_ticks() {
954        let mut g = game();
955        let initial = g.summary();
956        assert_eq!(
957            initial,
958            RoundSummary {
959                round: 1,
960                phase: Phase::Buy,
961                score: [0, 0],
962                remaining_seconds: 1.0,
963                countdown_seconds: Some(1),
964                last_outcome: None,
965                match_winner: None,
966            }
967        );
968        g.tick(0.75).unwrap();
969        assert_eq!(g.summary().remaining_seconds, 0.25);
970        assert_eq!(g.summary().countdown_seconds, Some(1));
971        assert_eq!(g.summary(), g.summary());
972        assert_eq!(g.pop_event(), Some(Event::RoundStarted(1)));
973        assert_eq!(g.pop_event(), None);
974        g.tick(0.25).unwrap();
975        assert_eq!(g.summary().phase, Phase::Live);
976        assert_eq!(g.summary().countdown_seconds, Some(10));
977        g.tick(0.25).unwrap();
978        assert_eq!(g.summary().remaining_seconds, 9.75);
979        assert_eq!(g.summary().countdown_seconds, Some(10));
980        assert_eq!(initial.phase, Phase::Buy);
981        assert_eq!(initial.remaining_seconds, 1.0);
982    }
983
984    #[test]
985    fn outcomes_survive_event_draining_and_are_replaced_on_the_next_result() {
986        let mut g = game();
987        g.tick(11.0).unwrap();
988        let first = RoundOutcome {
989            round: 1,
990            winner: Team::Defend,
991            reason: WinReason::TimeExpired,
992        };
993        assert_eq!(g.summary().phase, Phase::PostRound);
994        assert_eq!(g.summary().countdown_seconds, Some(1));
995        assert_eq!(g.summary().last_outcome, Some(first));
996        assert_eq!(g.summary().match_winner, None);
997        let events: Vec<_> = std::iter::from_fn(|| g.pop_event()).collect();
998        assert_eq!(
999            events,
1000            [
1001                Event::RoundStarted(1),
1002                Event::RoundWon {
1003                    team: first.winner,
1004                    reason: first.reason,
1005                },
1006            ]
1007        );
1008        g.tick(1.0).unwrap();
1009        assert_eq!(g.summary().round, 2);
1010        assert_eq!(g.summary().phase, Phase::Buy);
1011        assert_eq!(g.summary().last_outcome, Some(first));
1012        g.tick(1.0).unwrap();
1013        g.damage(1, 2, 100).unwrap();
1014        assert_eq!(
1015            g.summary().last_outcome,
1016            Some(RoundOutcome {
1017                round: 2,
1018                winner: Team::Attack,
1019                reason: WinReason::Elimination,
1020            })
1021        );
1022        assert_eq!(g.summary().score, [1, 1]);
1023        assert_eq!(g.damage(1, 2, 100), Err(RuleError::WrongPhase));
1024        assert_eq!(
1025            std::iter::from_fn(|| g.pop_event())
1026                .filter(|event| matches!(event, Event::RoundWon { .. }))
1027                .count(),
1028            1
1029        );
1030    }
1031
1032    #[test]
1033    fn bomb_outcome_summaries_agree_with_accepted_events_and_exact_ties() {
1034        for (delay, winner, reason) in [
1035            (0.0, Team::Defend, WinReason::Defused),
1036            (4.0, Team::Attack, WinReason::Explosion),
1037        ] {
1038            let mut g = game();
1039            g.tick(1.0).unwrap();
1040            g.act(1, Action::Plant(0)).unwrap();
1041            g.tick(2.0).unwrap();
1042            assert_eq!(g.summary().phase, Phase::Planted);
1043            assert_eq!(g.summary().countdown_seconds, Some(8));
1044            assert_eq!(g.summary().last_outcome, None);
1045            g.tick(delay).unwrap();
1046            g.act(2, Action::Defuse).unwrap();
1047            g.tick(4.0).unwrap();
1048            let summary = g.summary();
1049            assert_eq!(summary.phase, Phase::PostRound);
1050            assert_eq!(summary.countdown_seconds, Some(1));
1051            assert_eq!(
1052                summary.last_outcome,
1053                Some(RoundOutcome {
1054                    round: 1,
1055                    winner,
1056                    reason,
1057                })
1058            );
1059            let wins: Vec<_> = std::iter::from_fn(|| g.pop_event())
1060                .filter(|event| matches!(event, Event::RoundWon { .. }))
1061                .collect();
1062            assert_eq!(
1063                wins,
1064                [Event::RoundWon {
1065                    team: winner,
1066                    reason,
1067                }]
1068            );
1069            assert_eq!(g.summary(), summary);
1070        }
1071    }
1072
1073    #[test]
1074    fn match_winner_waits_for_intermission_and_terminal_ticks_emit_nothing() {
1075        let mut g = game();
1076        g.tick(23.0).unwrap();
1077        assert_eq!(g.summary().phase, Phase::PostRound);
1078        assert_eq!(g.summary().score, [0, 2]);
1079        assert_eq!(g.summary().match_winner, None);
1080        g.tick(1.0).unwrap();
1081        let finished = g.summary();
1082        assert_eq!(finished.phase, Phase::Finished);
1083        assert_eq!(finished.round, 2);
1084        assert_eq!(finished.remaining_seconds, 0.0);
1085        assert_eq!(finished.countdown_seconds, None);
1086        assert_eq!(finished.match_winner, Some(Team::Defend));
1087        assert_eq!(
1088            finished.last_outcome,
1089            Some(RoundOutcome {
1090                round: 2,
1091                winner: Team::Defend,
1092                reason: WinReason::TimeExpired,
1093            })
1094        );
1095        let events: Vec<_> = std::iter::from_fn(|| g.pop_event()).collect();
1096        assert_eq!(
1097            events,
1098            [
1099                Event::RoundStarted(1),
1100                Event::RoundWon {
1101                    team: Team::Defend,
1102                    reason: WinReason::TimeExpired,
1103                },
1104                Event::RoundStarted(2),
1105                Event::RoundWon {
1106                    team: Team::Defend,
1107                    reason: WinReason::TimeExpired,
1108                },
1109                Event::MatchWon(Team::Defend),
1110            ]
1111        );
1112        for _ in 0..3 {
1113            g.tick(0.0).unwrap();
1114            g.tick(3600.0).unwrap();
1115            g.forfeit(Team::Attack);
1116            g.forfeit(Team::Defend);
1117            assert_eq!(g.summary(), finished);
1118            assert_eq!(g.pop_event(), None);
1119        }
1120    }
1121
1122    fn game_in_phase(phase: Phase) -> TacticalMatch {
1123        let mut g = game();
1124        g.act(1, Action::BuyWeapon(Weapon::Rifle)).unwrap();
1125        g.act(2, Action::BuyArmor).unwrap();
1126        g.act(2, Action::BuyDefuseKit).unwrap();
1127        if phase != Phase::Buy {
1128            g.tick(1.0).unwrap();
1129            g.act(1, Action::Plant(0)).unwrap();
1130            g.tick(0.5).unwrap();
1131            if phase != Phase::Live {
1132                g.tick(1.5).unwrap();
1133                g.act(2, Action::Defuse).unwrap();
1134                g.tick(0.5).unwrap();
1135                if phase != Phase::Planted {
1136                    g.tick(1.5).unwrap();
1137                    if phase == Phase::Finished {
1138                        g.tick(13.0).unwrap();
1139                    }
1140                }
1141            }
1142        }
1143        assert_eq!(g.phase(), phase);
1144        g
1145    }
1146
1147    #[test]
1148    fn zero_and_invalid_ticks_preserve_every_phase_and_pending_interactions() {
1149        for phase in [
1150            Phase::Buy,
1151            Phase::Live,
1152            Phase::Planted,
1153            Phase::PostRound,
1154            Phase::Finished,
1155        ] {
1156            let mut g = game_in_phase(phase);
1157            let summary = g.summary();
1158            let progress = g.interaction_progress();
1159            let events = g.events.clone();
1160            for dt in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY, 3601.0] {
1161                let result = g.tick(dt);
1162                assert_eq!(
1163                    result,
1164                    if dt == 0.0 {
1165                        Ok(())
1166                    } else {
1167                        Err(RuleError::InvalidInput)
1168                    }
1169                );
1170                assert_eq!(g.summary(), summary);
1171                assert_eq!(g.interaction_progress(), progress);
1172                assert_eq!(g.events, events);
1173            }
1174        }
1175    }
1176
1177    #[test]
1178    fn forfeit_summaries_are_immediate_and_repeated_forfeits_are_no_ops() {
1179        for phase in [Phase::Buy, Phase::Live, Phase::Planted, Phase::PostRound] {
1180            let mut g = game_in_phase(phase);
1181            while g.pop_event().is_some() {}
1182            g.forfeit(Team::Attack);
1183            let summary = g.summary();
1184            assert_eq!(summary.phase, Phase::Finished);
1185            assert_eq!(summary.remaining_seconds, 0.0);
1186            assert_eq!(summary.countdown_seconds, None);
1187            assert_eq!(summary.score[1], 2);
1188            assert_eq!(summary.match_winner, Some(Team::Defend));
1189            assert_eq!(
1190                summary.last_outcome,
1191                Some(RoundOutcome {
1192                    round: 1,
1193                    winner: Team::Defend,
1194                    reason: WinReason::Forfeit,
1195                })
1196            );
1197            assert_eq!(g.interaction_progress(), None);
1198            g.forfeit(Team::Attack);
1199            g.forfeit(Team::Defend);
1200            assert_eq!(g.summary(), summary);
1201            assert_eq!(
1202                g.pop_event(),
1203                Some(Event::RoundWon {
1204                    team: Team::Defend,
1205                    reason: WinReason::Forfeit,
1206                })
1207            );
1208            assert_eq!(g.pop_event(), Some(Event::MatchWon(Team::Defend)));
1209            assert_eq!(g.pop_event(), None);
1210        }
1211    }
1212
1213    #[test]
1214    fn forfeit_winner_is_authoritative_even_when_final_scores_tie() {
1215        let mut g = game();
1216        g.tick(23.0).unwrap();
1217        // A clinching defender intermission is still eligible for a forfeit.
1218        g.forfeit(Team::Defend);
1219        assert_eq!(g.summary().score, [2, 2]);
1220        assert_eq!(g.summary().match_winner, Some(Team::Attack));
1221        assert_eq!(g.summary().last_outcome.unwrap().reason, WinReason::Forfeit);
1222    }
1223
1224    #[test]
1225    fn reset_restores_fresh_state_from_every_phase_and_reuses_storage() {
1226        for phase in [
1227            Phase::Buy,
1228            Phase::Live,
1229            Phase::Planted,
1230            Phase::PostRound,
1231            Phase::Finished,
1232        ] {
1233            let mut g = game_in_phase(phase);
1234            let fresh = game();
1235            let players_ptr = g.players.as_ptr();
1236            let players_capacity = g.players.capacity();
1237            let events_capacity = g.events.capacity();
1238            g.set_position(1, [5.0, 0.0, 0.0]).unwrap();
1239            if matches!(phase, Phase::Live | Phase::Planted) {
1240                g.damage(1, 2, 10).unwrap();
1241            } else {
1242                g.disconnect(2).unwrap();
1243            }
1244            assert_eq!(g.phase(), phase);
1245            for _ in 0..2 {
1246                g.reset();
1247                assert_eq!(g.summary(), fresh.summary());
1248                assert_eq!(g.interaction_progress(), None);
1249                assert_eq!(g.bomb(), fresh.bomb());
1250                assert_eq!(g.loss_streak, [0, 0]);
1251                assert_eq!(g.players.as_ptr(), players_ptr);
1252                assert_eq!(g.players.capacity(), players_capacity);
1253                assert_eq!(g.events.capacity(), events_capacity);
1254                for (player, expected) in g.players().iter().zip(fresh.players()) {
1255                    assert_eq!(player.id, expected.id);
1256                    assert_eq!(player.team, expected.team);
1257                    assert_eq!(player.spawn, expected.spawn);
1258                    assert_eq!(player.position, expected.position);
1259                    assert_eq!(player.health, expected.health);
1260                    assert_eq!(player.money, expected.money);
1261                    assert_eq!(player.weapon, expected.weapon);
1262                    assert_eq!(player.armor, expected.armor);
1263                    assert_eq!(player.defuse_kit, expected.defuse_kit);
1264                }
1265                assert_eq!(g.pop_event(), Some(Event::RoundStarted(1)));
1266                assert_eq!(g.pop_event(), None);
1267            }
1268            g.tick(11.0).unwrap();
1269            assert_eq!(g.score(), [0, 1]);
1270            assert_eq!(g.player(1).unwrap().money, 5400); // First-loss reward again.
1271        }
1272    }
1273
1274    #[test]
1275    fn reset_during_an_interaction_clears_channels_and_stale_events() {
1276        for phase in [Phase::Live, Phase::Planted] {
1277            let mut g = game_in_phase(phase);
1278            assert!(g.interaction_progress().is_some());
1279            g.reset();
1280            g.reset();
1281            assert_eq!(g.interaction_progress(), None);
1282            assert_eq!(g.pop_event(), Some(Event::RoundStarted(1)));
1283            assert_eq!(g.pop_event(), None);
1284            g.tick(3.0).unwrap();
1285            assert_eq!(g.phase(), Phase::Live);
1286            assert_eq!(g.remaining(), 8.0);
1287            assert_eq!(g.bomb(), Bomb::Carried(1));
1288            assert_eq!(g.player(1).unwrap().money, 4000);
1289            assert_eq!(g.pop_event(), None);
1290        }
1291    }
1292
1293    #[test]
1294    fn large_and_partitioned_ticks_have_identical_summaries_and_events() {
1295        let mut large = game();
1296        let mut partitioned = game();
1297        large.tick(24.0).unwrap();
1298        for _ in 0..96 {
1299            partitioned.tick(0.25).unwrap();
1300        }
1301        assert_eq!(large.summary(), partitioned.summary());
1302        assert_eq!(large.events, partitioned.events);
1303        assert_eq!(large.summary().phase, Phase::Finished);
1304    }
1305
1306    #[test]
1307    fn next_round_preserves_survivor_equipment_and_resets_dead_loadouts() {
1308        let mut g = game();
1309        g.act(1, Action::BuyWeapon(Weapon::Rifle)).unwrap();
1310        g.act(1, Action::BuyArmor).unwrap();
1311        g.act(2, Action::BuyWeapon(Weapon::Rifle)).unwrap();
1312        g.act(2, Action::BuyArmor).unwrap();
1313        g.act(2, Action::BuyDefuseKit).unwrap();
1314        g.tick(1.0).unwrap();
1315        g.set_position(1, [2.0, 0.0, 0.0]).unwrap();
1316        g.damage(1, 2, 200).unwrap();
1317        g.tick(1.0).unwrap();
1318        let survivor = g.player(1).unwrap();
1319        assert_eq!(survivor.weapon, Weapon::Rifle);
1320        assert_eq!(survivor.armor, 100);
1321        assert_eq!(survivor.position, survivor.spawn);
1322        let respawned = g.player(2).unwrap();
1323        assert_eq!(respawned.weapon, Weapon::Pistol);
1324        assert_eq!(respawned.armor, 0);
1325        assert!(!respawned.defuse_kit);
1326        assert_eq!(respawned.health, 100);
1327        assert_eq!(respawned.position, respawned.spawn);
1328        assert_eq!(g.bomb(), Bomb::Carried(1));
1329        assert_eq!(g.summary().round, 2);
1330    }
1331}