salvage_pinball/
lib.rs

1//! A small pinball table driven by Ferravex's original fixed-step physics world.
2//!
3//! [`PinballGame`] supplies the shared session lifecycle and render-frame input
4//! buffering; [`Table`] remains usable independently at a fixed timestep.
5mod game;
6pub use game::{PinballFeedback, PinballGame};
7
8use ferravex_physics::d2::{
9    ColliderBuilder, ColliderHandle, JointBuilder, PhysicsWorld, RigidBodyBuilder, RigidBodyHandle,
10    Vector,
11};
12
13use ferravex_physics::{JointHandle, JointMotor};
14
15// The ball interacts with table fixtures and flippers; capsule rails/flippers
16// do not have capsule/capsule contacts and cannot strike one another.
17const BALL_LAYER: u32 = 1;
18const FLIPPER_LAYER: u32 = 2;
19const FIXTURE_LAYER: u32 = 4;
20pub const BALL_RADIUS: f32 = 0.19;
21pub const FLIPPER_LENGTH: f32 = 1.65;
22pub const PIVOTS: [[f32; 2]; 2] = [[3.0, 13.2], [6.9, 13.2]];
23pub const BUMPERS: [[f32; 2]; 3] = [[2.6, 4.1], [6.2, 4.1], [4.4, 6.6]];
24/// Where the armed magnet crane catches the ball: the open top-centre lane.
25pub const CRANE: [f32; 2] = [4.4, 2.05];
26/// Catch radius around [`CRANE`] for the ball's centre.
27pub const CRANE_RADIUS: f32 = 0.5;
28/// Seconds the crane holds a caught ball before dropping it.
29pub const CRANE_HOLD: f32 = 1.2;
30/// Base points for a bumper contact before the yard multiplier.
31pub const BUMPER_POINTS: u32 = 100;
32/// Points for a launch whose first bumper contact is the lit skill-shot bumper.
33pub const SKILL_SHOT_POINTS: u32 = 1000;
34/// Jackpot points per multiplier step; a jackpot at x2 is worth 5,000.
35pub const JACKPOT_POINTS: u32 = 2500;
36/// One-time hidden award for keeping a single ball alive this long.
37pub const OVERTIME_SECONDS: f32 = 45.;
38pub const OVERTIME_POINTS: u32 = 5000;
39/// A bumper hit within this many seconds of the previous one extends a chain.
40pub const CHAIN_WINDOW: f32 = 1.2;
41pub const MAX_MULTIPLIER: u32 = 5;
42/// While a ball waits, the skill-shot lamp visits centre, right, then left.
43const SKILL_ORDER: [usize; 3] = [2, 1, 0];
44/// Seconds the skill-shot lamp rests on each bumper while a ball waits.
45pub const SKILL_STEP: f32 = 0.4;
46/// Capsule rails, also used by the renderer so collisions match the visible table.
47pub const RAILS: [([f32; 2], [f32; 2]); 13] = [
48    ([0.6, 2.0], [0.6, 11.6]),
49    ([0.6, 2.0], [1.8, 0.7]),
50    ([1.8, 0.7], [8.1, 0.7]),
51    ([8.1, 0.7], [9.7, 2.3]),
52    ([9.7, 2.3], [9.7, 15.1]),
53    ([8.8, 3.7], [8.8, 15.1]),
54    ([8.8, 15.1], [9.7, 15.1]),
55    ([0.6, 11.6], [3.0, 13.2]),
56    ([8.8, 11.6], [6.9, 13.2]),
57    ([1.2, 8.2], [2.7, 10.7]),
58    ([8.1, 8.2], [6.6, 10.7]),
59    ([2.7, 10.7], [2.9, 11.3]),
60    ([6.6, 10.7], [6.4, 11.3]),
61];
62
63/// Held flippers and a launch request. For [`Table::step`], launch is a one-tick
64/// command; [`PinballGame::advance`] accepts held input and buffers rising edges.
65#[derive(Clone, Copy, Debug, Default)]
66pub struct Controls {
67    pub left: bool,
68    pub right: bool,
69    pub launch: bool,
70}
71
72pub struct Table {
73    pub world: PhysicsWorld,
74    pub ball: RigidBodyHandle,
75    ball_collider: ColliderHandle,
76    flippers: [RigidBodyHandle; 2],
77    hinges: [JointHandle; 2],
78    bumpers: [ColliderHandle; 3],
79    contacts: [bool; 3],
80    // Accepted contact serials let presentation observe hits without changing
81    // the simulation's debounce or replaying a suppressed flash.
82    bumper_hits: [u64; 3],
83    ball_start_score: u32,
84    last_ball_points: Option<u32>,
85    /// Simulation debounce remaining for each powered bumper. Presentation
86    /// observes accepted hits separately; accessibility must not clear this.
87    pub bumper_flash: [f32; 3],
88    /// Time remaining for each bumper's readable, contact-confirmed +100 label.
89    pub bumper_notice: [f32; 3],
90    /// Time remaining for the last unsaved drain's next-ball prompt.
91    pub drain_notice: f32,
92    /// Controls actually applied to the flipper motors on the latest tick.
93    pub flipper_pressed: [bool; 2],
94    pub angles: [f32; 2],
95    pub score: u32,
96    pub lives: u8,
97    pub waiting: bool,
98    pub launches: u32,
99    pub hits: u32,
100    pub drains: u32,
101    pub saves: u32,
102    pub ball_save: f32,
103    pub save_notice: f32,
104    save_available: bool,
105    pub time: f32,
106    pub trail: [[f32; 2]; 12],
107    trail_tick: u32,
108    /// Yard multiplier for bumper points, `1..=MAX_MULTIPLIER`. Each crane
109    /// jackpot raises it; an unsaved drain resets it (a ball save keeps it).
110    pub multiplier: u32,
111    /// Bumper lamps lit toward the next crane. All three arm the crane.
112    pub lamps: [bool; 3],
113    /// An armed crane catches the ball near [`CRANE`] for a jackpot.
114    pub crane_armed: bool,
115    /// Seconds left holding a caught ball. The ball is pinned while positive.
116    pub crane_hold: f32,
117    /// Bumper hits in the current chain; zero once the chain window lapses.
118    pub chain: u32,
119    chain_timer: f32,
120    /// Longest chain this game.
121    pub best_chain: u32,
122    /// Bumper lit for the skill shot. Cycles while waiting, frozen in flight.
123    pub skill_target: usize,
124    /// True from a launch until the first bumper contact or the ball drops
125    /// into the lower playfield. The crane ignores a ball on its launch arc.
126    pub launch_flight: bool,
127    /// Seconds the current life has had a ball in play.
128    pub ball_time: f32,
129    /// The hidden overtime award has been collected this game.
130    pub overtime: bool,
131    pub jackpots: u32,
132    pub skill_shots: u32,
133    pub crane_arms: u32,
134    pub secrets: u32,
135    /// Points awarded by each bumper's latest accepted contact, including the
136    /// multiplier, chain bonus and skill shot. Presentation pops read this.
137    pub bumper_points: [u32; 3],
138    /// Points from the most recent jackpot.
139    pub last_jackpot: u32,
140}
141
142impl Default for Table {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148impl Table {
149    pub fn new() -> Self {
150        let mut world = PhysicsWorld::new([0.0, 10.5]);
151        for (a, b) in RAILS {
152            world.raw.insert(
153                RigidBodyBuilder::fixed(),
154                ColliderBuilder::capsule_from_endpoints(
155                    Vector::from_array(a),
156                    Vector::from_array(b),
157                    0.1,
158                )
159                .collision_layers(FIXTURE_LAYER, BALL_LAYER)
160                .restitution(0.65)
161                .friction(0.08),
162            );
163        }
164        let bumpers = BUMPERS.map(|p| {
165            world
166                .raw
167                .insert(
168                    RigidBodyBuilder::fixed().translation(Vector::from_array(p)),
169                    ColliderBuilder::ball(0.61)
170                        .collision_layers(FIXTURE_LAYER, BALL_LAYER)
171                        .restitution(0.9)
172                        .friction(0.02),
173                )
174                .1
175        });
176        let angles = [0.4, std::f32::consts::PI - 0.4];
177        let flippers = std::array::from_fn(|i| {
178            world
179                .raw
180                .insert(
181                    RigidBodyBuilder::dynamic()
182                        .gravity_scale(0.)
183                        .ccd_enabled(true)
184                        .angular_damping(0.4)
185                        .translation(Vector::from_array(PIVOTS[i]))
186                        .rotation(angles[i]),
187                    ColliderBuilder::capsule_from_endpoints(
188                        Vector::ZERO,
189                        Vector::new(FLIPPER_LENGTH, 0.0),
190                        0.16,
191                    )
192                    .collision_layers(FLIPPER_LAYER, BALL_LAYER)
193                    .density(4.)
194                    .friction(0.15)
195                    .restitution(0.45),
196                )
197                .0
198        });
199        let anchor = world.insert_body(RigidBodyBuilder::fixed()).unwrap();
200        let hinges = std::array::from_fn(|i| {
201            world
202                .insert_joint(
203                    anchor,
204                    flippers[i],
205                    JointBuilder::hinge()
206                        .local_anchor1(Vector::from_array(PIVOTS[i]))
207                        .limits(
208                            if i == 0 { -1. } else { -0.15 },
209                            if i == 0 { 0.15 } else { 1. },
210                        )
211                        .motor(JointMotor::position(0., 40., 18., 1000.)),
212                )
213                .unwrap()
214        });
215        let (ball, ball_collider) = Self::spawn_ball(&mut world);
216        Self {
217            world,
218            ball,
219            ball_collider,
220            flippers,
221            hinges,
222            bumpers,
223            angles,
224            contacts: [false; 3],
225            bumper_hits: [0; 3],
226            ball_start_score: 0,
227            last_ball_points: None,
228            bumper_flash: [0.0; 3],
229            bumper_notice: [0.0; 3],
230            drain_notice: 0.,
231            flipper_pressed: [false; 2],
232            score: 0,
233            lives: 3,
234            waiting: true,
235            launches: 0,
236            hits: 0,
237            drains: 0,
238            saves: 0,
239            ball_save: 0.,
240            save_notice: 0.,
241            save_available: true,
242            time: 0.0,
243            trail: [[9.25, 14.4]; 12],
244            trail_tick: 0,
245            multiplier: 1,
246            lamps: [false; 3],
247            crane_armed: false,
248            crane_hold: 0.,
249            chain: 0,
250            chain_timer: 0.,
251            best_chain: 0,
252            skill_target: SKILL_ORDER[0],
253            launch_flight: false,
254            ball_time: 0.,
255            overtime: false,
256            jackpots: 0,
257            skill_shots: 0,
258            crane_arms: 0,
259            secrets: 0,
260            bumper_points: [0; 3],
261            last_jackpot: 0,
262        }
263    }
264
265    /// Points the next plain bumper contact is worth at the current multiplier.
266    pub fn bumper_value(&self) -> u32 {
267        BUMPER_POINTS * self.multiplier
268    }
269
270    /// Extra points a hit would add as the `chain`-th consecutive contact.
271    /// Chains of three or more pay an escalating bonus, capped at 500.
272    ///
273    /// ```
274    /// use salvage_pinball::Table;
275    /// assert_eq!(Table::chain_bonus(2), 0);
276    /// assert_eq!(Table::chain_bonus(3), 50);
277    /// assert_eq!(Table::chain_bonus(40), 500);
278    /// ```
279    pub fn chain_bonus(chain: u32) -> u32 {
280        (chain.saturating_sub(2) * 50).min(500)
281    }
282
283    /// Accepted bumper contact: scoring, lamps, chain and the skill shot.
284    fn bumper_hit(&mut self, i: usize) {
285        self.chain = if self.chain_timer > 0. {
286            self.chain + 1
287        } else {
288            1
289        };
290        self.chain_timer = CHAIN_WINDOW;
291        self.best_chain = self.best_chain.max(self.chain);
292        let mut points = self.bumper_value() + Self::chain_bonus(self.chain);
293        if self.launch_flight {
294            self.launch_flight = false;
295            if i == self.skill_target {
296                self.skill_shots += 1;
297                points += SKILL_SHOT_POINTS;
298            }
299        }
300        self.score += points;
301        self.bumper_points[i] = points;
302        if !self.crane_armed {
303            self.lamps[i] = true;
304            if self.lamps == [true; 3] {
305                self.crane_armed = true;
306                self.crane_arms += 1;
307            }
308        }
309    }
310
311    /// Pin a caught ball to the magnet, or drop it once the hold expires.
312    fn crane(&mut self, dt: f32) {
313        let ball = &mut self.world.bodies[self.ball];
314        if self.crane_hold > 0. {
315            self.crane_hold = (self.crane_hold - dt).max(0.);
316            if self.crane_hold > 0. {
317                ball.set_translation(Vector::from_array(CRANE), true);
318                ball.set_linvel(Vector::ZERO, true);
319            } else {
320                // Alternate the drop so repeated jackpots do not replay one path.
321                let side = if self.jackpots.is_multiple_of(2) {
322                    1.
323                } else {
324                    -1.
325                };
326                ball.set_gravity_scale(1.0, true);
327                ball.set_linvel(Vector::new(side * 1.1, 1.5), true);
328            }
329            return;
330        }
331        let near = (ball.translation() - Vector::from_array(CRANE)).length() < CRANE_RADIUS;
332        if self.crane_armed && !self.launch_flight && !self.waiting && near {
333            self.crane_armed = false;
334            self.crane_hold = CRANE_HOLD;
335            self.jackpots += 1;
336            self.last_jackpot = JACKPOT_POINTS * self.multiplier;
337            self.score += self.last_jackpot;
338            self.multiplier = (self.multiplier + 1).min(MAX_MULTIPLIER);
339            self.lamps = [false; 3];
340            ball.set_gravity_scale(0., true);
341            ball.set_translation(Vector::from_array(CRANE), true);
342            ball.set_linvel(Vector::ZERO, true);
343        }
344    }
345
346    fn spawn_ball(world: &mut PhysicsWorld) -> (RigidBodyHandle, ColliderHandle) {
347        world.raw.insert(
348            RigidBodyBuilder::dynamic()
349                .translation(Vector::new(9.25, 14.4))
350                .gravity_scale(0.0)
351                .ccd_enabled(true)
352                .linear_damping(0.03),
353            ColliderBuilder::ball(BALL_RADIUS)
354                .collision_layers(BALL_LAYER, FIXTURE_LAYER | FLIPPER_LAYER)
355                .density(2.0)
356                .friction(0.08)
357                .restitution(0.5),
358        )
359    }
360
361    pub fn position(&self) -> [f32; 2] {
362        self.world.bodies[self.ball].translation().to_array()
363    }
364
365    pub fn over(&self) -> bool {
366        self.lives == 0
367    }
368
369    /// Points recovered on the current life, including any saved/re-served ball.
370    /// An unsaved drain banks the total and starts the next life at zero. This
371    /// is a score breakdown, not an extra bonus award; it is zero after game-over.
372    ///
373    /// ```
374    /// use salvage_pinball::{Controls, PinballGame};
375    /// let mut game = PinballGame::new(false);
376    /// assert_eq!(game.table().ball_points(), 0);
377    /// game.advance(1.0 / 120.0, Controls { launch: true, ..Default::default() });
378    /// assert_eq!(game.table().ball_points(), 0); // launching does not score
379    /// ```
380    pub fn ball_points(&self) -> u32 {
381        self.score.saturating_sub(self.ball_start_score)
382    }
383
384    /// Total recovered on the most recently drained, unsaved life. Saves leave
385    /// this unchanged; a fresh table has no completed life. Reading it consumes
386    /// no event and never awards those points a second time.
387    ///
388    /// ```
389    /// use salvage_pinball::{Controls, Table};
390    /// let mut table = Table::new();
391    /// assert_eq!(table.last_ball_points(), None);
392    /// // Put the ball past the drain and execute an actual physics tick.
393    /// table.world.bodies[table.ball].set_translation([4.9, 17.2].into(), true);
394    /// table.step(1.0 / 120.0, Controls::default());
395    /// assert_eq!(table.last_ball_points(), Some(0));
396    /// assert_eq!(table.lives, 2);
397    /// ```
398    pub fn last_ball_points(&self) -> Option<u32> {
399        self.last_ball_points
400    }
401
402    /// An automatic player presses the same controls as a human, with no ball steering.
403    pub fn autoplay(&self) -> Controls {
404        let p = self.position();
405        let descending = self.world.bodies[self.ball].linvel().y > 0.0;
406        let ready = p[1] > 12.95 && descending;
407        Controls {
408            left: ready && p[0] > 3.6 && p[0] < 5.6,
409            right: ready && p[0] > 4.2 && p[0] < 6.3,
410            launch: self.waiting,
411        }
412    }
413
414    pub fn step(&mut self, dt: f32, controls: Controls) {
415        if self.over() {
416            return;
417        }
418        self.time += dt;
419        self.ball_save = (self.ball_save - dt).max(0.);
420        self.save_notice = (self.save_notice - dt).max(0.);
421        self.drain_notice = (self.drain_notice - dt).max(0.);
422        self.chain_timer = (self.chain_timer - dt).max(0.);
423        if self.chain_timer == 0. {
424            self.chain = 0;
425        }
426        if self.waiting {
427            let step = (self.time / SKILL_STEP) as usize;
428            self.skill_target = SKILL_ORDER[step % SKILL_ORDER.len()];
429        }
430        for (i, pressed) in [controls.left, controls.right].into_iter().enumerate() {
431            self.flipper_pressed[i] = pressed;
432            let target = if pressed {
433                if i == 0 { -0.9 } else { 0.9 }
434            } else {
435                0.
436            };
437            self.world.joints[self.hinges[i]]
438                .set_motor(Some(JointMotor::position(
439                    target,
440                    if pressed { 60. } else { 40. },
441                    if pressed { 22. } else { 12. },
442                    if pressed { 1600. } else { 1000. },
443                )))
444                .unwrap();
445        }
446        if controls.launch && self.waiting {
447            self.waiting = false;
448            self.launches += 1;
449            self.launch_flight = true;
450            if self.save_available {
451                self.ball_save = 5.;
452                self.save_available = false;
453            }
454            let ball = &mut self.world.bodies[self.ball];
455            ball.set_gravity_scale(1.0, true);
456            ball.apply_impulse(Vector::new(0.0, -25.0) * ball.mass(), true);
457        }
458        self.crane(dt);
459        self.world.step(dt);
460        for i in 0..2 {
461            self.angles[i] = self.world.bodies[self.flippers[i]].rotation().angle();
462        }
463        for (i, bumper) in self.bumpers.into_iter().enumerate() {
464            self.bumper_flash[i] = (self.bumper_flash[i] - dt).max(0.0);
465            self.bumper_notice[i] = (self.bumper_notice[i] - dt).max(0.0);
466            let touching = self
467                .world
468                .raw
469                .contact_pair(self.ball_collider, bumper)
470                .is_some_and(|pair| pair.has_any_active_contact());
471            if touching && !self.contacts[i] && self.bumper_flash[i] <= 0.0 {
472                self.bumper_hit(i);
473                self.hits += 1;
474                self.bumper_hits[i] = self.bumper_hits[i].wrapping_add(1);
475                self.bumper_flash[i] = 0.18;
476                self.bumper_notice[i] = 0.75;
477                let ball = &mut self.world.bodies[self.ball];
478                let outward = (ball.translation() - Vector::from_array(BUMPERS[i]))
479                    .try_normalize()
480                    .unwrap_or(Vector::new(0.0, -1.0));
481                // The powered pop bumper adds energy at actual physical contact.
482                ball.apply_impulse(outward * ball.mass() * 7.5, true);
483            }
484            self.contacts[i] = touching;
485        }
486        // Powered bumpers/flippers can add energy, but a readable table needs a
487        // ceiling. Apply this after real contacts rather than steering the ball.
488        let ball = &mut self.world.bodies[self.ball];
489        let bounded = ball.linvel().clamp_length_max(34.);
490        if bounded != ball.linvel() {
491            ball.set_linvel(bounded, true);
492        }
493        self.trail_tick += 1;
494        if self.trail_tick.is_multiple_of(3) {
495            self.trail.rotate_right(1);
496            self.trail[0] = self.position();
497        }
498        let p = self.position();
499        if self.launch_flight && p[1] > 4.8 && p[0] < 8.7 {
500            // The launch arc missed every bumper and fell into the playfield.
501            self.launch_flight = false;
502        }
503        if !self.waiting {
504            self.ball_time += dt;
505            if !self.overtime && self.ball_time >= OVERTIME_SECONDS {
506                self.overtime = true;
507                self.secrets += 1;
508                self.score += OVERTIME_POINTS;
509            }
510        }
511        if !self.waiting
512            && p[0] > 8.95
513            && p[1] > 14.2
514            && self.world.bodies[self.ball].linvel().length() < 1.5
515        {
516            // A ball that falls back into the real launch lane can be served again.
517            self.waiting = true;
518            self.launch_flight = false;
519        }
520        if p[1] > 16.0 || p[0] < -1.0 || p[0] > 11.0 {
521            let saved = self.ball_save > 0.;
522            if saved {
523                self.saves += 1;
524                self.save_notice = 2.;
525            } else {
526                self.last_ball_points = Some(self.ball_points());
527                self.ball_start_score = self.score;
528                self.lives -= 1;
529                self.save_available = true;
530                self.drain_notice = 2.5;
531                self.save_notice = 0.;
532                self.multiplier = 1;
533                self.lamps = [false; 3];
534                self.crane_armed = false;
535                self.ball_time = 0.;
536            }
537            self.chain = 0;
538            self.chain_timer = 0.;
539            self.crane_hold = 0.;
540            self.launch_flight = false;
541            self.ball_save = 0.;
542            self.drains += 1;
543            if self.lives > 0 {
544                self.world.raw.remove_body(self.ball);
545                (self.ball, self.ball_collider) = Self::spawn_ball(&mut self.world);
546                self.contacts = [false; 3];
547                self.waiting = true;
548                self.trail = [self.position(); 12];
549            }
550        }
551    }
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    #[test]
559    fn early_drain_saves_once_and_powered_contacts_have_a_speed_ceiling() {
560        let mut table = Table::new();
561        table.step(
562            DT,
563            Controls {
564                launch: true,
565                ..Default::default()
566            },
567        );
568        table.world.bodies[table.ball].set_translation(Vector::new(4.9, 16.2), true);
569        table.world.bodies[table.ball].set_linvel(Vector::new(0., 8.), true);
570        table.step(DT, Controls::default());
571        assert_eq!((table.saves, table.lives), (1, 3));
572        assert!(table.waiting);
573        table.step(
574            DT,
575            Controls {
576                launch: true,
577                ..Default::default()
578            },
579        );
580        table.world.bodies[table.ball].set_translation(Vector::new(4.9, 16.2), true);
581        table.world.bodies[table.ball].set_linvel(Vector::new(0., 8.), true);
582        table.step(DT, Controls::default());
583        assert_eq!((table.saves, table.lives), (1, 2));
584        table.world.bodies[table.ball].set_linvel(Vector::new(-100., 0.), true);
585        table.step(DT, Controls::default());
586        assert!(table.world.bodies[table.ball].linvel().length() <= 34.01);
587    }
588
589    const DT: f32 = 1.0 / 120.0;
590
591    #[test]
592    fn launch_is_gated_and_uses_impulse() {
593        let mut table = Table::new();
594        for _ in 0..30 {
595            table.step(DT, Controls::default());
596        }
597        assert_eq!(table.launches, 0);
598        assert!((table.position()[1] - 14.4).abs() < 0.01);
599        let launch = Controls {
600            launch: true,
601            ..Controls::default()
602        };
603        table.step(DT, launch);
604        assert!(table.world.bodies[table.ball].linvel().y < -20.0);
605        table.step(DT, launch);
606        assert_eq!(table.launches, 1);
607    }
608
609    #[test]
610    fn bumper_scores_on_real_contact_not_proximity() {
611        let mut table = Table::new();
612        table.waiting = false;
613        table.world.bodies[table.ball].set_translation(Vector::new(2.6, 3.0), true);
614        table.step(DT, Controls::default());
615        assert_eq!(table.score, 0);
616        table.world.bodies[table.ball].set_translation(Vector::new(2.6, 3.32), true);
617        table.world.bodies[table.ball].set_linvel(Vector::new(0.0, 2.0), true);
618        table.step(DT, Controls::default());
619        assert_eq!(table.score, 100);
620        assert!(table.world.bodies[table.ball].linvel().y < 0.0);
621        for _ in 0..10 {
622            table.step(DT, Controls::default());
623        }
624        assert_eq!(table.score, 100);
625    }
626
627    #[test]
628    fn three_drains_end_game_without_duplicate_life_loss() {
629        let mut table = Table::new();
630        for lives in [2, 1, 0] {
631            table.world.bodies[table.ball].set_translation(Vector::new(4.9, 16.2), true);
632            table.step(DT, Controls::default());
633            assert_eq!(table.lives, lives);
634        }
635        for _ in 0..120 {
636            table.step(DT, Controls::default());
637        }
638        assert_eq!(table.drains, 3);
639        assert!(table.over());
640    }
641
642    #[test]
643    fn moving_flipper_transfers_energy_to_ball() {
644        let mut table = Table::new();
645        table.waiting = false;
646        table.world.bodies[table.ball].set_translation(Vector::new(4.1, 13.25), true);
647        for _ in 0..8 {
648            table.step(
649                DT,
650                Controls {
651                    left: true,
652                    ..Controls::default()
653                },
654            );
655        }
656        assert!(table.world.bodies[table.ball].linvel().y < -1.0);
657        assert!(table.angles[0] < 0.0);
658    }
659
660    #[test]
661    fn both_flippers_attack_promptly_and_return_when_released() {
662        let mut table = Table::new();
663        for _ in 0..6 {
664            table.step(
665                DT,
666                Controls {
667                    left: true,
668                    right: true,
669                    launch: false,
670                },
671            );
672        }
673        assert!(
674            table.angles[0] < -0.15,
675            "left flipper should rise within 50ms: {:?}",
676            table.angles
677        );
678        assert!(table.angles[1].sin() < -0.15, "right tip must also rise");
679        assert_eq!(table.flipper_pressed, [true; 2]);
680        for _ in 0..30 {
681            table.step(DT, Controls::default());
682        }
683        assert!((table.angles[0] - 0.4).abs() < 0.03);
684        assert!((table.angles[1] - (std::f32::consts::PI - 0.4)).abs() < 0.03);
685        assert_eq!(table.flipper_pressed, [false; 2]);
686    }
687
688    /// Teleport onto a bumper's top and run one tick, as the presentation tests do.
689    fn touch_bumper(table: &mut Table, bumper: usize) -> u32 {
690        let before = table.score;
691        table.bumper_flash = [0.; 3];
692        let [x, y] = BUMPERS[bumper];
693        table.world.bodies[table.ball].set_translation(Vector::new(x, y - 0.78), true);
694        table.world.bodies[table.ball].set_linvel(Vector::new(0., 2.), true);
695        table.step(DT, Controls::default());
696        table.score - before
697    }
698
699    fn park(table: &mut Table) {
700        // Away from every bumper and outside the crane's catch zone.
701        table.world.bodies[table.ball].set_translation(Vector::new(7.4, 6.6), true);
702        table.world.bodies[table.ball].set_linvel(Vector::ZERO, true);
703        table.step(DT, Controls::default());
704    }
705
706    fn drain(table: &mut Table) {
707        table.world.bodies[table.ball].set_translation(Vector::new(4.9, 16.2), true);
708        table.world.bodies[table.ball].set_linvel(Vector::new(0., 8.), true);
709        table.step(DT, Controls::default());
710    }
711
712    #[test]
713    fn three_lamps_arm_the_crane_which_pays_a_jackpot_and_raises_the_multiplier() {
714        let mut table = Table::new();
715        table.waiting = false;
716        for bumper in [0, 0, 1] {
717            touch_bumper(&mut table, bumper);
718            park(&mut table);
719            for _ in 0..(CHAIN_WINDOW / DT) as usize {
720                table.step(DT, Controls::default());
721                table.world.bodies[table.ball].set_translation(Vector::new(7.4, 6.6), true);
722            }
723        }
724        assert_eq!(table.lamps, [true, true, false]);
725        assert!(!table.crane_armed);
726        assert_eq!(touch_bumper(&mut table, 2), 100, "chain lapsed: plain hit");
727        assert!(table.crane_armed);
728        assert_eq!(table.crane_arms, 1);
729        // While armed, further hits keep the lamps lit without re-arming.
730        park(&mut table);
731        touch_bumper(&mut table, 0);
732        assert_eq!(table.crane_arms, 1);
733
734        let before = table.score;
735        table.world.bodies[table.ball].set_translation(Vector::from_array(CRANE), true);
736        table.world.bodies[table.ball].set_linvel(Vector::new(3., -4.), true);
737        table.step(DT, Controls::default());
738        assert_eq!(table.jackpots, 1);
739        assert_eq!(table.score - before, JACKPOT_POINTS);
740        assert_eq!(table.last_jackpot, JACKPOT_POINTS);
741        assert_eq!(table.multiplier, 2);
742        assert_eq!(table.lamps, [false; 3]);
743        assert!(!table.crane_armed && table.crane_hold > 0.);
744        // The magnet holds the ball still, then drops it back into play.
745        for _ in 0..(CRANE_HOLD / DT) as usize - 2 {
746            table.step(DT, Controls::default());
747            assert_eq!(table.position(), CRANE);
748        }
749        for _ in 0..60 {
750            table.step(DT, Controls::default());
751        }
752        assert_eq!(table.crane_hold, 0.);
753        assert!(table.position()[1] > CRANE[1] + 0.5, "dropped ball falls");
754        assert_eq!(table.jackpots, 1, "no re-catch without re-arming");
755        assert_eq!(table.bumper_value(), 200);
756    }
757
758    #[test]
759    fn launch_arc_ignores_the_crane_and_the_skill_shot_needs_the_lit_bumper() {
760        // Launch while the centre lamp is lit: the arc always reaches the left
761        // bumper first, so there is no skill shot, and an armed crane on the
762        // arc's path does not catch the ball.
763        let mut table = Table::new();
764        table.crane_armed = true;
765        table.step(
766            DT,
767            Controls {
768                launch: true,
769                ..Default::default()
770            },
771        );
772        assert_eq!(table.skill_target, 2);
773        assert!(table.launch_flight);
774        let mut first = None;
775        for _ in 0..400 {
776            table.step(DT, Controls::default());
777            if table.hits > 0 {
778                first = Some(table.score);
779                break;
780            }
781        }
782        assert_eq!(first, Some(100));
783        assert_eq!((table.skill_shots, table.jackpots), (0, 0));
784        assert!(!table.launch_flight);
785
786        // Wait for the hopping lamp to reach the left bumper, then launch.
787        let mut table = Table::new();
788        while table.skill_target != 0 {
789            table.step(DT, Controls::default());
790        }
791        table.step(
792            DT,
793            Controls {
794                launch: true,
795                ..Default::default()
796            },
797        );
798        for _ in 0..400 {
799            table.step(DT, Controls::default());
800            if table.hits > 0 {
801                break;
802            }
803        }
804        assert_eq!(table.skill_shots, 1);
805        assert_eq!(table.score, 100 + SKILL_SHOT_POINTS);
806        assert_eq!(table.bumper_points[0], 100 + SKILL_SHOT_POINTS);
807    }
808
809    #[test]
810    fn quick_hits_build_a_capped_chain_bonus_that_lapses() {
811        let mut table = Table::new();
812        table.waiting = false;
813        let mut paid = Vec::new();
814        for bumper in [0, 1, 0, 1, 0] {
815            paid.push(touch_bumper(&mut table, bumper));
816            park(&mut table);
817        }
818        assert_eq!(paid, [100, 100, 150, 200, 250]);
819        assert_eq!((table.chain, table.best_chain), (5, 5));
820        for _ in 0..(CHAIN_WINDOW / DT) as usize + 1 {
821            table.step(DT, Controls::default());
822            table.world.bodies[table.ball].set_translation(Vector::new(7.4, 6.6), true);
823        }
824        assert_eq!(table.chain, 0);
825        assert_eq!(touch_bumper(&mut table, 1), 100);
826        assert_eq!(table.best_chain, 5);
827    }
828
829    #[test]
830    fn a_save_keeps_the_multiplier_but_an_unsaved_drain_resets_the_ball_rules() {
831        let mut table = Table::new();
832        table.step(
833            DT,
834            Controls {
835                launch: true,
836                ..Default::default()
837            },
838        );
839        table.multiplier = 3;
840        table.lamps = [true, false, true];
841        drain(&mut table);
842        assert_eq!((table.saves, table.lives), (1, 3));
843        assert_eq!(table.multiplier, 3);
844        assert_eq!(table.lamps, [true, false, true]);
845        table.step(
846            DT,
847            Controls {
848                launch: true,
849                ..Default::default()
850            },
851        );
852        table.crane_armed = true;
853        drain(&mut table);
854        assert_eq!(table.lives, 2);
855        assert_eq!(table.multiplier, 1);
856        assert_eq!(table.lamps, [false; 3]);
857        assert!(!table.crane_armed);
858        assert_eq!((table.chain, table.ball_time), (0, 0.));
859    }
860
861    #[test]
862    fn overtime_secret_pays_once_per_game_on_a_long_ball() {
863        let mut table = Table::new();
864        table.waiting = false;
865        let mut paid = 0;
866        for _ in 0..((OVERTIME_SECONDS + 20.) / DT) as usize {
867            // Hold the ball still away from everything; only time passes.
868            table.world.bodies[table.ball].set_translation(Vector::new(7.4, 6.6), true);
869            table.world.bodies[table.ball].set_linvel(Vector::ZERO, true);
870            let before = table.score;
871            table.step(DT, Controls::default());
872            paid += table.score - before;
873        }
874        assert!(table.overtime);
875        assert_eq!((table.secrets, paid), (1, OVERTIME_POINTS));
876        drain(&mut table);
877        for _ in 0..((OVERTIME_SECONDS + 1.) / DT) as usize {
878            table.waiting = false;
879            table.world.bodies[table.ball].set_translation(Vector::new(7.4, 6.6), true);
880            table.step(DT, Controls::default());
881        }
882        assert_eq!(table.secrets, 1, "one secret per game");
883    }
884
885    #[test]
886    fn autoplay_plays_real_table_and_scores() {
887        let mut table = Table::new();
888        for _ in 0..7200 {
889            let input = table.autoplay();
890            table.step(DT, input);
891            assert!(table.position().into_iter().all(f32::is_finite));
892        }
893        eprintln!(
894            "pinball: score={} hits={} launches={} drains={}",
895            table.score, table.hits, table.launches, table.drains
896        );
897        assert!(table.launches > 0);
898        assert!(
899            table.hits >= 2,
900            "autoplay should reach and hit the bumper field"
901        );
902    }
903}
904
905mod app;
906#[cfg(not(target_arch = "wasm32"))]
907pub use app::run;