# 6. Space Invaders Tests Polish and Pitfalls Part of [[Space Invaders]]. Previous: [[5. Space Invaders Score Lives Waves and HUD]]. ## 6.1 Tests Put `FormationModel.cs` and `GameSession.cs` in a `SpaceInvaders.Core` assembly definition (No Engine References), and the tests in an Edit Mode test assembly that references it ([[Unity Test Framework]]). ```csharp using System; using NUnit.Framework; public sealed class SpaceInvadersModelTests { static FormationModel Rack() => new FormationModel(5, 11, 0.5f, 0.45f, -3.4f, 3.4f, stepX: 0.125f, dropY: 0.25f); [Test] public void FullRack_StartsSlow_LastInvaderIsFastest() { var m = Rack(); Assert.AreEqual(55, m.AliveCount); Assert.AreEqual(0.8f, m.StepInterval, 1e-5f); for (var r = 0; r < 5; r++) for (var c = 0; c < 11; c++) if (!(r == 4 && c == 5)) m.Kill(r, c); Assert.AreEqual(1, m.AliveCount); Assert.AreEqual(0.05f, m.StepInterval, 1e-5f); } [Test] public void Kill_IsIdempotent() { var m = Rack(); Assert.IsTrue(m.Kill(2, 3)); Assert.IsFalse(m.Kill(2, 3)); Assert.AreEqual(54, m.AliveCount); } [Test] public void Rack_BouncesAtRightEdge_DropsAndReverses() { var m = Rack(); m.Reset(-2.5f, 3.2f); var drops = 0; m.Dropped += () => drops++; // Rightmost invader starts at -2.5 + 10*0.5 = 2.5; 0.9 of room / 0.125 = 7 steps, the 8th drops. for (var i = 0; i < 7; i++) m.Step(); Assert.AreEqual(0, drops); Assert.AreEqual(1, m.Direction); m.Step(); Assert.AreEqual(1, drops); Assert.AreEqual(-1, m.Direction); Assert.AreEqual(2.95f, m.Y(0), 1e-4f); Assert.AreEqual(-1.625f, m.OriginX, 1e-4f, "drop step doesn't move sideways"); } [Test] public void EmptyEdgeColumns_LetTheRackTravelFurther() { var m = Rack(); m.Reset(-2.5f, 3.2f); for (var r = 0; r < 5; r++) m.Kill(r, 10); // clear the rightmost column var steps = 0; var dropped = false; m.Dropped += () => dropped = true; while (!dropped && steps < 100) { m.Step(); steps++; } Assert.AreEqual(12, steps, "rightmost live column now starts at 2.0: 11 steps, the 12th drops"); } [Test] public void Tick_StepsOnInterval_AndCapsCatchUp() { var m = Rack(); Assert.AreEqual(0, m.Tick(0.79f)); Assert.AreEqual(1, m.Tick(0.02f)); Assert.AreEqual(4, m.Tick(10f), "a 10 s hitch takes at most 4 steps"); } [Test] public void OnlyBottomInvaderShoots_AimPicksNearestColumn() { var m = Rack(); m.Reset(-2.5f, 3.2f); m.Kill(4, 0); Assert.AreEqual(3, m.BottomRow(0)); for (var r = 0; r < 5; r++) m.Kill(r, 1); Assert.AreEqual(-1, m.BottomRow(1)); var rng = new Random(1); Assert.AreEqual(2, m.PickShooterColumn(rng, -1.9f, 1f), "column 1 (x=-2.0) is empty; nearest live column to x=-1.9 is 2 (x=-1.5), not 0 (x=-2.5)"); for (var i = 0; i < 200; i++) Assert.AreNotEqual(1, m.PickShooterColumn(rng, 0f, 0f), "never an empty column"); } [Test] public void LowestY_TracksTheBottomLivingRow() { var m = Rack(); m.Reset(0f, 3f); Assert.AreEqual(3f - 4 * 0.45f, m.LowestY(), 1e-4f); for (var c = 0; c < 11; c++) m.Kill(4, c); Assert.AreEqual(3f - 3 * 0.45f, m.LowestY(), 1e-4f); } [Test] public void RowPoints_MatchTheArcade() { Assert.AreEqual(30, GameSession.PointsForRow(0, 5)); Assert.AreEqual(20, GameSession.PointsForRow(1, 5)); Assert.AreEqual(20, GameSession.PointsForRow(2, 5)); Assert.AreEqual(10, GameSession.PointsForRow(3, 5)); Assert.AreEqual(10, GameSession.PointsForRow(4, 5)); Assert.AreEqual(990, 11 * 30 + 22 * 20 + 22 * 10, "a full rack is worth 990"); } [Test] public void ExtraLife_OnceAt1500_HighScoreFollows() { var s = new GameSession(3, highScore: 1000); s.AddScore(1490); Assert.AreEqual(3, s.Lives); Assert.AreEqual(1490, s.HighScore); s.AddScore(10); Assert.AreEqual(4, s.Lives); s.AddScore(5000); Assert.AreEqual(4, s.Lives, "only one bonus life"); } [Test] public void Lives_GameOver_AndInvasion() { var s = new GameSession(2); s.LoseLife(); Assert.IsFalse(s.IsGameOver); s.LoseLife(); Assert.IsTrue(s.IsGameOver); s.AddScore(100); Assert.AreEqual(0, s.Score, "no score after game over"); s.NewGame(); s.Invaded(); Assert.IsTrue(s.IsGameOver); } [Test] public void UfoPoints_CycleWithShots_WaveDropIsCapped() { Assert.AreEqual(50, GameSession.UfoPoints(0)); Assert.AreEqual(300, GameSession.UfoPoints(3)); Assert.AreEqual(50, GameSession.UfoPoints(4)); Assert.AreEqual(0f, GameSession.WaveStartDrop(1, 0.25f), 1e-6f); Assert.AreEqual(0.5f, GameSession.WaveStartDrop(3, 0.25f), 1e-6f); Assert.AreEqual(1.5f, GameSession.WaveStartDrop(50, 0.25f), 1e-6f); } } ``` > [!note] Test status (2026-12-01) > These 11 tests passed on .NET 10 (with a tiny stand-in for NUnit's `Assert`) against these exact files. The file type-checks against Unity 6000.5.8f1's NUnit but **was not run in the Unity Test Runner**. > > One test caught a mistake in the *test*: with column 1 empty and the player at x −2.0, columns 0 and 2 are exactly the same distance away, and the model (correctly) picks the first. The test now uses x −1.9. Ties go to the lower column, which is worth knowing when you tune `aimChance`. The edge test encodes the arithmetic. The rightmost invader starts at x 2.5 and the bound is 3.4, so there's 0.9 units of room. At 0.125 per step that's 7 steps, and the 8th drops. Clearing the right column moves the rightmost live invader to 2.0, giving 11 steps then a drop. Strategy you can test. ## 6.2 Polish (in order of payoff) 1. **Explosion sprites** that linger 0.2 s where an invader died (pool them). 2. **The cannon explosion**: flash for `respawnSeconds`, then reappear centred. 3. **Screen shake on cannon death only.** Shaking on every invader kill gets tiring. 4. **The march sound gets faster on its own**, because it's tied to steps. Don't add music on top of it. 5. **Colour bands** in the original's overlay style: green below the bunkers, red at the top (the UFO lane). The sprites stay white and a tint does it. 6. **Attract mode**: after game over, show the score table and "INSERT COIN", then demo-play using the replay recorder. ## 6.3 Design lens From [[Level Up! (Review)]]: - **Readable threats.** Every danger is a white shape on black. Keep it that way. Don't add particle noise around invader shots. - **Risk and reward.** The UFO is worth up to 300, but shooting it means leaving cover. Bunkers make "where do I stand" a real choice. - **Difficulty that follows skill.** The speed-up is a self-adjusting difficulty curve. New players face a slow rack for longer because they kill slowly. The wave drop is the second, slower ramp. ## 6.4 Pitfalls | Pitfall | Symptom | Fix | |---|---|---| | Static invaders vs static bunker cells | Rack passes through bunkers without erasing them | Kinematic Rigidbody2D (full kinematic contacts) on invader prefabs (part 3 note) | | Bullet is kinematic without full contacts | Shots pass through everything | `useFullKinematicContacts = true` (the `Bullet` sets it), or add bodies to targets | | Collision matrix too open | Invader shots kill invaders, or shots hit shots | Matrix from part 1; `FromPlayer` checks as a backstop | | Rack checks bounds with *all* columns | Rack turns early after you clear an edge | Use live columns only (`FindLiveColumns`) | | Uncapped catch-up | Rack teleports after a hitch | `Tick` caps at 4 steps | | Bilinear filtering on sprites | Blurry pixel art | Point filter, no compression, Pixel Perfect Camera | | `Instantiate` per shot | GC spikes | `ObjectPool<Bullet>` | | Ticking the rack while the cannon respawns | Unfair deaths right after respawn | Director freezes the rack while `IsDead` | | UFO component disabled when hidden | It never comes back | Toggle renderer and collider, not the GameObject | | High score lost on quit | | `PlayerPrefs.Save()` on game over | ## 6.5 Where next - Port the HUD to a pixel font and a USS theme. - Record runs and play ghost demos in attract mode ([[Replays and Ghost Recording]]). - Ship a WebGL build ([[Web and WebGL Builds]], [[Publishing to itch.io and Steam]]).