Найти в Дзене
KNL Games

Создание полноценной игры «Сапёр» на C# с использованием WPF

Создание полноценной игры «Сапёр» на C# с использованием WPF — это сложная задача, которая требует много времени и усилий. Ниже представлен упрощённый пример того, как можно начать создание такой игры.

Графическая составляющая игры:

MainWindow.xaml

<Window x:Class="Minesweeper.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Сапёр" Height="450" Width="800">
<
Grid x:Name="gameGrid" />
</
Window>

Программная составляющая игры:

MainWindow.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;

namespace Minesweeper
{
public partial class MainWindow : Window
{
private const int Rows = 10;
private const int Columns = 10;
private const int Mines = 10;

private bool[,] mines;
private int[,] numbers;

public MainWindow()
{
InitializeComponent();
InitializeGame();
}

private void InitializeGame()
{
mines =
new bool[Rows, Columns];
numbers =
new int[Rows, Columns];

// Расстановка мин
for (int i = 0; i < Mines; i++)
{
int x =
new Random().Next(Rows);
int y =
new Random().Next(Columns);

while (mines[x, y])
{
x =
new Random().Next(Rows);
y =
new Random().Next(Columns);
}

mines[x, y] = true;
}

// Подсчёт чисел
for (int x = 0; x < Rows; x++)
{
for (int y = 0; y < Columns; y++)
{
if (mines[x, y]) continue;

int count = 0;
for (int dx = -1; dx <= 1; dx++)
{
for (int dy = -1; dy <= 1; dy++)
{
if (x + dx < 0 || x + dx >= Rows) continue;
if (y + dy < 0 || y + dy >= Columns) continue;
if (mines[x + dx, y + dy]) count++;
}
}
numbers[x, y] = count;
}
}

// Создание сетки
gameGrid.RowDefinitions.Clear();
gameGrid.ColumnDefinitions.Clear();
for (int i = 0; i < Rows; i++)
{
gameGrid.RowDefinitions.Add(
new RowDefinition());
}
for (int j = 0; j < Columns; j++)
{
gameGrid.ColumnDefinitions.Add(
new ColumnDefinition());
}

// Добавление кнопок
for (int x = 0; x < Rows; x++)
{
for (int y = 0; y < Columns; y++)
{
Button button =
new Button();
button.Click += Button_Click;
Grid.SetRow(button, x);
Grid.SetColumn(button, y);
gameGrid.Children.Add(button);
}
}
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
int x = Grid.GetRow(button);
int y = Grid.GetColumn(button);

if (mines[x, y])
{
button.Content = "💣";
MessageBox.Show("Вы проиграли!");
InitializeGame();
}
else
{
button.Content = numbers[x, y].ToString();
}
}
}
}

Этот код создаёт базовую версию игры «Сапёр» с сеткой кнопок, которые можно нажимать. При нажатии на кнопку проверяется, есть ли под ней мина, и если да, то игра заканчивается.