Skip to content

About

Cross-platform arcade game built with C# (.NET 9), Uno Platform, SkiaSharp hardware-accelerated rendering, and MVVM architecture.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Space Invaders (.NET 9 / Uno Platform)

.NET 9 Uno Platform SkiaSharp Language MVVM

A high-performance, cross-platform recreation of the iconic 1978 arcade classic Space Invaders, engineered in C# / .NET 9 utilizing Uno Platform and hardware-accelerated Skia canvas rendering.


📖 Table of Contents


1. Overview & Historical Context

What is Space Invaders?

Originally designed by Tomohiro Nishikado and released by Taito in 1978, Space Invaders established the blueprint for the shoot 'em up (shmup) genre and fixed-screen arcade games. It introduced foundational video game concepts such as dynamic pacing, destructible defensive cover, continuous audio that accelerates with gameplay tension, and scaling difficulty driven by entity count.

Core Objective & Rules

The player pilots a ground-based Laser Cannon moving horizontally across the bottom of the screen, tasked with eliminating descending matrix formations of extraterrestrial invaders before they reach Earth's surface.

Key pillars:

  • Horizontal Traversal & Single-Shot Discipline: The cannon navigates within fixed left/right boundaries and must time shots strategically.
  • Defensive Erosion: Deployable modular bunkers absorb incoming and outgoing fire, gradually deteriorating.
  • Dynamic Tension: As the alien matrix thins out, the remaining invaders march faster, dropping lower on every wall rebound.
  • Dual Loss Condition: The game terminates when the player depletes all lives or when any invader successfully reaches the defense baseline.

2. Game Logic & Technical Deep Dive

+-------------------------------------------------------------------------------+
|                                  GameManager                                  |
|  +-------------------------------------------------------------------------+  |
|  |                        GameLoop (20ms / 50Hz)                           |  |
|  |  +---------------------+  +---------------------+  +-----------------+  |  |
|  |  | UpdatePlayerPosition|  | UpdateSwarmPosition |  |   UpdateUfo     |  |  |
|  |  +----------+----------+  +----------+----------+  +--------+--------+  |  |
|  |             |                        |                      |           |  |
|  |  +----------v----------+  +----------v----------+  +--------v--------+  |  |
|  |  |   MoveBullets       |  | HandleEnemyShooting |  | CheckCollisions |  |  |
|  |  +---------------------+  +---------------------+  +-----------------+  |  |
|  +-------------------------------------------------------------------------+  |
|         |                                      |                     |        |
|  +------v------+                        +------v------+       +------v------+ |
|  | PlayerModel |                        | EnemyManager|       | BarrierGrid | |
|  +-------------+                        +-------------+       +-------------+ |
+-------------------------------------------------------------------------------+

Game Loop & State Management

The core simulation is driven by DispatcherTimer in GameManager.cs operating at a fixed tick interval of 20 milliseconds ($\approx 50\text{ Hz}$ update frequency).

Application state transitions are orchestrated via the MVVM pattern using GameViewModel.cs:

  • Start Screen (IsStartScreenVisible): Renders the title banner, score reference index, and high-score navigation.
  • Active Gameplay (IsGameScreenVisible): Canvas-driven frame updates, entity physics, and audio hooks.
  • Pause Overlay (IsPauseScreenVisible): Suspends the simulation timer and halts looped audio playback.
  • High Score Board (IsHighScoreScreenVisible): Displays top 10 historical scores persisted to disk.
  • Game Over Screen (IsGameOverScreenVisible): Presents outcome state (Victory vs. Defeat), final tally, and name input for leaderboard entry.

Entity Architecture & Hierarchy

Every visual game actor inherits from the abstract base class GameObject.cs:

          +-----------------------+
          |      GameObject       |
          |-----------------------|
          | + Visual: UIElement   |
          | + Width: double       |
          | + Height: double      |
          | + X: double           |
          | + Y: double           |
          +-----------+-----------+
                      |
     +----------------+----------------+----------------+
     |                |                |                |
+----v-----+    +-----v------+   +-----v------+   +-----v--------+
|  Player  |    |   Enemy    |   |    Ufo     |   | BarrierBlock |
+----------+    +------------+   +------------+   +--------------+

Each entity synchronizes logical coordinates directly to the Uno Canvas layout engine using attached properties Canvas.Left and Canvas.Top.

Alien Swarm Movement & Acceleration Curve

The alien swarm is instantiated by EnemyManager.cs as a 5-row $\times$ 10-column matrix (50 total enemies):

  • Row 0 (Top): alien3 (Squid variant, 40 Points)
  • Rows 1–2 (Middle): alien2 (Crab variant, 20 Points each)
  • Rows 3–4 (Bottom): alien1 (Octopus variant, 10 Points each)

March Pattern & Step-Down Mechanics:

  1. The swarm steps horizontally by a stride of $\Delta X = 12\text{ px}$.
  2. On every tick interval, the manager computes a projected step for every living invader.
  3. If any alien's boundary intersects screen edges ($X < 0$ or $X + \text{Width} > \text{CanvasWidth}$):
    • Direction flag _movingRight is inverted (!_movingRight).
    • Swarm descends vertically by SwarmMoveDownStep = 20 px.
  4. If any alien reaches the defense perimeter ($Y + \text{Height} \ge 550\text{ px}$), AliensHaveLanded triggers an immediate Defeat condition.

Dynamic Acceleration Formula:

The movement delay interval ($\Delta T_{\text{move}}$) dynamically shrinks proportionally to the remaining alien ratio:

$$\Delta T_{\text{move}} = \left(\frac{N_{\text{remaining}}}{N_{\text{total}}} \times 0.6\right) + 0.04\quad\text{(seconds)}$$

  • Full Swarm ($N=50$): $\Delta T \approx 0.640\text{ s}$ per step (slow, rhythmic march).
  • Single Alien Remaining ($N=1$): $\Delta T \approx 0.052\text{ s}$ per step ($\approx 19.2\text{ steps/s}$, ultra-rapid panic pace).

Shooting Subsystem & Projectile Lifecycles

               [ Upward: Player Laser (-15 px/tick) ]
                                 ▲
                                 |
 [ Cannon ] -------------------------------------------------> [ Enemy Formation ]
                                 |
                                 ▼
              [ Downward: Enemy Bomb (+5 px/tick) ]
  • Player Laser:
    • Velocity: $-15\text{ px/tick}$ (upward).
    • Concurrency: Limited to 1 active laser on screen at any given moment, enforcing high-precision shooting.
    • Bullet Size: $5\text{ px} \times 15\text{ px}$, rendered in #7CFC00 (Lawn Green).
  • Enemy Bombardment:
    • Velocity: $+5\text{ px/tick}$ (downward).
    • Firing Probability: Evaluated each tick with a $2%$ chance per frame ($0.02$).
    • Targeting: GetRandomShooter() randomly selects a surviving enemy from the remaining active swarm.
    • Bullet Size: $5\text{ px} \times 15\text{ px}$, rendered in #FFFFFF (White).

Collision Detection & Spatial Mathematics

Collision checking in GameManager.cs utilizes exact 2D Axis-Aligned Bounding Box (AABB) intersection testing:

private bool CheckCollision(FrameworkElement a, FrameworkElement b)
{
    double ax = Canvas.GetLeft(a);
    double ay = Canvas.GetTop(a);
    double bx = Canvas.GetLeft(b);
    double by = Canvas.GetTop(b);

    return ax < bx + b.Width &&
           ax + a.Width > bx &&
           ay < by + b.Height &&
           ay + a.Height > by;
}

Collision Resolution Matrix:

Source Collider Target Collider Resolution Action
Player Laser Enemy Enemy removed, score awarded, sound triggered, laser recycled, extra life checked.
Player Laser UFO UFO destroyed, randomized bonus (50–300 pts) awarded, laser recycled.
Enemy Bomb Player Player loses 1 life, enters Stun State ($50\text{ ticks}$, 50% opacity blink). If $\text{Lives} = 0 \to \text{GameOver}$.
Any Laser / Bomb Barrier Block Block loses $1\text{ HP}$, updates color shade, destroyed at $0\text{ HP}$. Projectile is consumed.

Destructible Shield / Barrier Mechanics

The battlefield features 3 protective bunkers positioned at X coordinates 100, 355, and 610 ($Y = 450\text{ px}$).

  +---+---+---+---+---+---+
  | # | # | # | # | # | # |   Row 0 (Solid)
  +---+---+---+---+---+---+
  | # | # | # | # | # | # |   Row 1 (Solid)
  +---+---+---+---+---+---+
  | # | # | # | # | # | # |   Row 2 (Solid)
  +---+---+---+---+---+---+
  | # |   |   |   |   | # |   Row 3 (Archway cutout)
  +---+---+---+---+---+---+

Each barrier is constructed as a composite matrix of $15\text{ px} \times 15\text{ px}$ sub-blocks (BarrierBlock.cs):

  • Health Points: Each sub-block possesses $3\text{ HP}$.
  • Damage-State Color Shading:
    • $3\text{ HP}$ (Full): #7CFC00 (Bright Green)
    • $2\text{ HP}$ (Damaged): #60C000 (Medium Green)
    • $1\text{ HP}$ (Critical): #408000 (Dark Olive Green)
    • $0\text{ HP}$ (Destroyed): Removed from the visual tree and collision buffer.

Mystery UFO Ship

  • Spawn Timer: Randomized cooldown between $500$ and $1000\text{ ticks}$ ($10\text{ s} - 20\text{ s}$).
  • Trajectory: Traverses the upper canvas perimeter horizontally at $Y = 30\text{ px}$ with $\text{Speed} = 3\text{ px/tick}$.
  • Reward: Random reward distribution selected on instantiation: ${50, 100, 150, 200, 300}\text{ pts}$.

Scoring, Wave Progression & Extra Lives

  • Enemy Scoring Values:
    • Alien Type 1 (Octopus): 10 pts
    • Alien Type 2 (Crab): 20 pts
    • Alien Type 3 (Squid): 40 pts
    • UFO Mystery Ship: 50–300 pts
  • Wave Respawn Loop: When IsSwarmDestroyed evaluates to true, SpawnWave() regenerates the full 50-invader formation, resets the movement step timer, and preserves current player score and lives.
  • Extra Life Milestone: A bonus life is granted upon reaching score thresholds every $1,000\text{ points}$ (capped at a maximum of $6\text{ lives}$).

3. Tech Stack & Dependencies

Category Technology Purpose
Runtime & Language C# 13 / .NET 9.0 (net9.0-desktop) Core execution runtime and modern language features
UI & Host Framework Uno Platform (v6.1.23) Cross-platform UI single-project abstraction
Graphics Engine SkiaSharp / Skia Renderer Hardware-accelerated 2D canvas drawing on desktop
Architecture CommunityToolkit.Mvvm Decoupled MVVM state handling, commands, and code generation
Audio Engine NAudio (v2.2.1) Low-latency audio playback (WaveOutEvent, AudioFileReader, LoopStream)
Supported Platforms Linux (X11 / FrameBuffer), Windows (Win32), macOS Desktop deployment targets

4. Project Architecture & Directory Structure

spaceinvaders/
├── Directory.Build.props            # Shared project build properties
├── Directory.Packages.props         # Central package management (CPM)
├── global.json                      # MSBuild SDK configuration (Uno.Sdk 6.1.23)
├── SpaceInvaders.sln                # Master solution file
└── SpaceInvaders/
    ├── App.xaml / App.xaml.cs       # Application entry point & Uno initialization
    ├── MainPage.xaml / .xaml.cs     # Main XAML visual hierarchy & keyboard router
    ├── SpaceInvaders.csproj         # Project configuration (net9.0-desktop, SkiaRenderer)
    │
    ├── Assets/                      # Static game media assets
    │   ├── Images/                  # Sprites (alien1-4.png, lasercannon.png, etc.)
    │   └── Sounds/                  # Audio tracks (shoot.mp3, hit.mp3, barrier.mp3, etc.)
    │
    ├── Converters/                  # XAML UI Converters
    │   └── BooleanToVisibilityConverter.cs
    │
    ├── Models/                      # Game entity models
    │   ├── GameObject.cs            # Abstract base entity with coordinate bindings
    │   ├── Player.cs                # Laser cannon entity, lives, stun logic
    │   ├── Enemy.cs                 # Individual invader representation
    │   ├── EnemyType.cs             # Alien metadata (point value, sprite path)
    │   ├── BarrierBlock.cs          # 15x15 destructible shield sub-unit with health states
    │   ├── Ufo.cs                   # Top-lane bonus ship model
    │   └── HighScoreEntry.cs        # Leaderboard data transfer object
    │
    ├── Platforms/Desktop/
    │   └── Program.cs               # Host bootstrap (X11, Win32, MacOS, LinuxFrameBuffer)
    │
    ├── Services/                    # Core gameplay subsystems
    │   ├── GameManager.cs           # Primary engine, tick loop, collision logic, input dispatcher
    │   ├── EnemyManager.cs          # Swarm generation, matrix traversal, acceleration curve
    │   ├── SoundManager.cs          # NAudio wave output and looped sound effects
    │   └── ScoreService.cs          # CSV file persistence and leaderboard ranking
    │
    └── ViewModels/                  # Presentation state
        └── GameViewModel.cs         # MVVM commands, UI visibility bindings, high score view

5. Getting Started & Execution

Prerequisites

Install the following before cloning the project:

  • Git to clone the repository.
  • .NET 9 SDK version 9.0.100 or newer. The runtime alone is not sufficient because the project must be compiled locally.
  • A desktop environment supported by Uno Platform:
    • Windows: Win32 desktop host.
    • Linux: X11 or XWayland. A native Wayland-only session is not currently used by this project.
    • macOS: native macOS desktop host.

Verify that the SDK is available:

dotnet --version

The command must report a 9.0.x SDK. You can use dotnet --list-sdks to inspect all installed versions if a different version is selected.

Audio compatibility: the current sound implementation uses NAudio's WaveOutEvent, which is designed for Windows. The game can run on Linux and macOS, but sound playback may be unavailable on those systems until a cross-platform audio backend is added.

First-time Setup

Clone the repository, enter its root directory, and restore the NuGet packages:

git clone https://github.com/Empty7k/spaceinvaders.git
cd spaceinvaders
dotnet restore SpaceInvaders/SpaceInvaders.csproj

The first restore downloads the Uno Platform SDK and its transitive dependencies, so it can take several minutes and use a few gigabytes of disk space in the global NuGet cache.

Compile the desktop target to verify the setup:

dotnet build SpaceInvaders/SpaceInvaders.csproj -f net9.0-desktop --no-restore

A successful build ends with 0 Error(s) and creates the application under SpaceInvaders/bin/Debug/net9.0-desktop/.

Running from the Command Line

dotnet run --project SpaceInvaders/SpaceInvaders.csproj -f net9.0-desktop

Run this command from the repository root. dotnet run automatically rebuilds the project when source files have changed.

Running from an IDE

JetBrains Rider can open the solution on Windows, Linux, and macOS. Visual Studio can be used on Windows.

  1. Open SpaceInvaders.sln.
  2. Allow the IDE to restore the NuGet packages when prompted.
  3. Select SpaceInvaders (Desktop) as the startup profile.
  4. Build and run the project.

No IDE is required; the .NET CLI commands above provide the complete build and execution workflow.

Troubleshooting

The Uno.Sdk cannot be found

Confirm that the computer can access https://api.nuget.org and run the restore again:

dotnet restore SpaceInvaders/SpaceInvaders.csproj --force

The application does not open on Linux

The desktop host requires an X11 display. Confirm that DISPLAY is set:

echo "$DISPLAY"

When using Wayland, ensure that XWayland is installed and enabled by your distribution.

A previous build is stale or corrupted

Clean the generated output, restore the dependencies, and rebuild:

dotnet clean SpaceInvaders/SpaceInvaders.csproj -f net9.0-desktop
dotnet restore SpaceInvaders/SpaceInvaders.csproj
dotnet build SpaceInvaders/SpaceInvaders.csproj -f net9.0-desktop --no-restore

Controls & Input Mapping

Key Binding Action
← / A Move Cannon Left
→ / D Move Cannon Right
Space Fire Laser (1 shot on screen at a time)
Esc Pause / Resume Active Game
Enter / UI Buttons Submit High Score / Navigate Menus

6. Persistence & High Scores

High scores are persisted to a local flat-file (highscores.txt) in the application runtime directory:

  • Format: Comma-separated records formatted as PLAYER_NAME,SCORE.
  • Ordering: Sorted descending by score via LINQ upon load and mutation.
  • Capacity: Retains the top 10 entries.
  • Fallback Initialization: Auto-generates default sample scores (CPU, ACE, BOT) if no file exists.

About

Cross-platform arcade game built with C# (.NET 9), Uno Platform, SkiaSharp hardware-accelerated rendering, and MVVM architecture.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages