Simple Snake Game in C# WinUI 3 (.NET 9)
Here's a basic implementation of the Snake game using WinUI 3 with .NET 9. This example uses the new features of C# 13 where applicable.
1. Create a new WinUI 3 project
First, create a new WinUI 3 project using the project template in Visual Studio.
2. MainWindow.xaml
<Window
x:Class="SnakeGame.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SnakeGame"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Snake Game"
Width="800"
Height="600">
<Grid>
<Canvas x:Name="GameCanvas" Background="Black"/>
<TextBlock x:Name="ScoreText" HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0,10,10,0" Foreground="White" FontSize="24"/>
<Button x:Name="StartButton" Content="Start Game" HorizontalAlignment="Center"
VerticalAlignment="Center" Click="StartButton_Click"/>
</Grid>
</Window>
3. MainWindow.xaml.cs
using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Shapes;
using System;
using System.Collections.Generic;
using System.Numerics;
using Windows.System;
namespace SnakeGame;
public sealed partial class MainWindow : Window
{
private const int CellSize = 20;
private const int GridWidth = 30;
private const int GridHeight = 20;
private DispatcherTimer _gameTimer = new();
private Vector2 _direction = new(1, 0);
private Vector2 _nextDirection = new(1, 0);
private Vector2 _foodPosition;
private readonly List<Vector2> _snake = [];
private bool _isGameRunning = false;
private int _score = 0;
private readonly Random _random = new();
public MainWindow()
{
InitializeComponent();
_gameTimer.Interval = TimeSpan.FromMilliseconds(100);
_gameTimer.Tick += GameLoop;
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
StartGame();
}
private void StartGame()
{
GameCanvas.Children.Clear();
_snake.Clear();
// Initialize snake with 3 segments
_snake.Add(new Vector2(5, 10));
_snake.Add(new Vector2(4, 10));
_snake.Add(new Vector2(3, 10));
_direction = new Vector2(1, 0);
_nextDirection = new Vector2(1, 0);
_score = 0;
ScoreText.Text = $"Score: {_score}";
SpawnFood();
DrawGame();
_isGameRunning = true;
_gameTimer.Start();
StartButton.Visibility = Visibility.Collapsed;
}
private void GameLoop(object? sender, object e)
{
if (!_isGameRunning) return;
_direction = _nextDirection;
MoveSnake();
CheckCollision();
DrawGame();
}
private void MoveSnake()
{
// Create new head
Vector2 newHead = _snake[0] + _direction;
// Add new head
_snake.Insert(0, newHead);
// Check if snake ate food
if (newHead == _foodPosition)
{
_score++;
ScoreText.Text = $"Score: {_score}";
SpawnFood();
}
else
{
// Remove tail if no food was eaten
_snake.RemoveAt(_snake.Count - 1);
}
}
private void CheckCollision()
{
Vector2 head = _snake[0];
// Check wall collision
if (head.X < 0 || head.X >= GridWidth || head.Y < 0 || head.Y >= GridHeight)
{
GameOver();
return;
}
// Check self collision (skip head)
for (int i = 1; i < _snake.Count; i++)
{
if (head == _snake[i])
{
GameOver();
return;
}
}
}
private void SpawnFood()
{
List<Vector2> possiblePositions = [];
// Generate all possible positions not occupied by snake
for (int x = 0; x < GridWidth; x++)
{
for (int y = 0; y < GridHeight; y++)
{
Vector2 pos = new(x, y);
if (!_snake.Contains(pos))
{
possiblePositions.Add(pos);
}
}
}
if (possiblePositions.Count > 0)
{
_foodPosition = possiblePositions[_random.Next(possiblePositions.Count)];
}
else
{
// No space left - player wins!
GameOver();
}
}
private void DrawGame()
{
GameCanvas.Children.Clear();
// Draw snake
foreach (Vector2 segment in _snake)
{
Rectangle rect = new()
{
Width = CellSize,
Height = CellSize,
Fill = new SolidColorBrush(Colors.LimeGreen)
};
Canvas.SetLeft(rect, segment.X * CellSize);
Canvas.SetTop(rect, segment.Y * CellSize);
GameCanvas.Children.Add(rect);
}
// Draw food
Rectangle foodRect = new()
{
Width = CellSize,
Height = CellSize,
Fill = new SolidColorBrush(Colors.Red)
};
Canvas.SetLeft(foodRect, _foodPosition.X * CellSize);
Canvas.SetTop(foodRect, _foodPosition.Y * CellSize);
GameCanvas.Children.Add(foodRect);
}
private void GameOver()
{
_isGameRunning = false;
_gameTimer.Stop();
StartButton.Content = "Game Over! Play Again?";
StartButton.Visibility = Visibility.Visible;
}
protected override void OnKeyDown(Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
{
if (!_isGameRunning) return;
switch (e.Key)
{
case VirtualKey.Up when _direction.Y != 1:
_nextDirection = new Vector2(0, -1);
break;
case VirtualKey.Down when _direction.Y != -1:
_nextDirection = new Vector2(0, 1);
break;
case VirtualKey.Left when _direction.X != 1:
_nextDirection = new Vector2(-1, 0);
break;
case VirtualKey.Right when _direction.X != -1:
_nextDirection = new Vector2(1, 0);
break;
}
}
}
Features of this implementation:
-
Basic Snake Game Mechanics:
- Snake moves continuously in the current direction
- Player controls direction with arrow keys
- Snake grows when eating food
- Game ends when hitting walls or self
-
WinUI 3 Specifics:
- Uses Canvas for drawing game elements
- DispatcherTimer for game loop
- Vector2 from System.Numerics for position handling
-
C# 13 Features:
- Collection expressions (
[]) for list initialization
- Simplified null checks
-
Game UI:
- Start/restart button
- Score display
- Simple visual elements (rectangles for snake and food)
How to Play:
- Click "Start Game" button
- Use arrow keys to control snake direction
- Eat the red food to grow and increase score
- Avoid hitting walls or yourself
You can enhance this basic implementation by:
- Adding difficulty levels (speed increases with score)
- Adding sound effects
- Implementing a high score system
- Adding pause functionality
- Improving graphics with custom shapes or images