Document code style and normalize files

This commit is contained in:
2026-05-08 21:10:46 +02:00
parent 2e813962c9
commit 5a261f5fe2
20 changed files with 1033 additions and 388 deletions

View File

@@ -1,6 +1,6 @@
namespace ReactorMaintenance.Simulation;
namespace ReactorMaintenance.Simulation;
public enum EditorTool
public enum EEditorTool
{
Floor,
Wall,
@@ -22,90 +22,76 @@ public enum EditorTool
public static class LevelEditor
{
public static LevelState Apply(LevelState level, GridPosition position, EditorTool tool)
public static LevelState Apply(LevelState level, GridPosition position, EEditorTool tool)
{
if (!level.InBounds(position))
return level;
if (tool == EditorTool.Robot)
if (tool == EEditorTool.Robot)
return level.GetCell(position).IsWalkable ? level with { Robot = position } : level;
var cell = level.GetCell(position);
cell = tool switch
{
EditorTool.Floor => cell with { Kind = CellKind.Floor },
EditorTool.Wall => cell with
{
Kind = CellKind.Wall,
Pipe = PipeMedium.None,
cell = tool switch {
EEditorTool.Floor => cell with { Kind = ECellKind.Floor },
EEditorTool.Wall => cell with {
Kind = ECellKind.Wall,
Pipe = EPipeMedium.None,
Powered = false
},
EditorTool.Reactor => cell with { Kind = CellKind.Reactor },
EditorTool.CoolingPump => cell with
{
Kind = CellKind.CoolingPump,
EEditorTool.Reactor => cell with { Kind = ECellKind.Reactor },
EEditorTool.CoolingPump => cell with {
Kind = ECellKind.CoolingPump,
Powered = true
},
EditorTool.Generator => cell with
{
Kind = CellKind.Generator,
EEditorTool.Generator => cell with {
Kind = ECellKind.Generator,
Powered = true
},
EditorTool.PressureRegulator => cell with { Kind = CellKind.PressureRegulator },
EditorTool.DiagnosticTerminal => cell with
{
Kind = CellKind.DiagnosticTerminal,
EEditorTool.PressureRegulator => cell with { Kind = ECellKind.PressureRegulator },
EEditorTool.DiagnosticTerminal => cell with {
Kind = ECellKind.DiagnosticTerminal,
Powered = true
},
EditorTool.ControlTerminal => cell with
{
Kind = CellKind.ControlTerminal,
EEditorTool.ControlTerminal => cell with {
Kind = ECellKind.ControlTerminal,
Powered = true
},
EditorTool.CoolantPipe => cell with
{
Pipe = PipeMedium.Coolant,
EEditorTool.CoolantPipe => cell with {
Pipe = EPipeMedium.Coolant,
Flow = 4,
Pressure = 4,
Integrity = Math.Max(cell.Integrity, 8),
PipeOpen = true
},
EditorTool.FuelPipe => cell with
{
Pipe = PipeMedium.Fuel,
EEditorTool.FuelPipe => cell with {
Pipe = EPipeMedium.Fuel,
Flow = 4,
Pressure = 4,
Integrity = Math.Max(cell.Integrity, 8),
PipeOpen = true
},
EditorTool.PressurePipe => cell with
{
Pipe = PipeMedium.Pressure,
EEditorTool.PressurePipe => cell with {
Pipe = EPipeMedium.Pressure,
Flow = 5,
Pressure = 6,
Integrity = Math.Max(cell.Integrity, 8),
PipeOpen = true
},
EditorTool.Leak => cell with
{
EEditorTool.Leak => cell with {
LeakRate = Math.Max(1, cell.LeakRate),
Integrity = Math.Min(cell.Integrity, 4)
},
EditorTool.Repair => cell with
{
EEditorTool.Repair => cell with {
LeakRate = 0,
Integrity = 10,
Hazards = cell.Hazards with
{
Hazards = cell.Hazards with {
Fire = false,
ElectricalCharge = 0
}
},
EditorTool.Heat => cell with { Hazards = cell.Hazards with { Heat = Rules.Clamp(cell.Hazards.Heat + 2) } },
EditorTool.Fire => cell with
{
Hazards = cell.Hazards with
{
EEditorTool.Heat => cell with { Hazards = cell.Hazards with { Heat = Rules.Clamp(cell.Hazards.Heat + 2) } },
EEditorTool.Fire => cell with {
Hazards = cell.Hazards with {
Fire = !cell.Hazards.Fire,
Heat = Math.Max(cell.Hazards.Heat, 7),
Smoke = Math.Max(cell.Hazards.Smoke, 3)
@@ -114,7 +100,7 @@ public static class LevelEditor
_ => cell
};
if (cell.Kind == CellKind.Wall)
if (cell.Kind == ECellKind.Wall)
cell = cell with { Hazards = new() };
return level.SetCell(position, cell);

View File

@@ -1,4 +1,4 @@
using System.Text.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ReactorMaintenance.Simulation;
@@ -13,15 +13,10 @@ public static class LevelSerializer
public static LevelState Deserialize(string json)
{
var level = JsonSerializer.Deserialize<LevelState>(json, Options) ?? throw new InvalidOperationException("Level file did not contain a level.");
if (level.Cells.Length != level.Width * level.Height)
throw new InvalidOperationException("Level cell count does not match its dimensions.");
return level;
return level.Cells.Length != level.Width * level.Height ? throw new InvalidOperationException("Level cell count does not match its dimensions.") : level;
}
private static readonly JsonSerializerOptions Options = new()
{
private static readonly JsonSerializerOptions Options = new() {
WriteIndented = true,
Converters = { new JsonStringEnumConverter() }
};

View File

@@ -1,6 +1,6 @@
namespace ReactorMaintenance.Simulation;
namespace ReactorMaintenance.Simulation;
public enum CellKind
public enum ECellKind
{
Empty,
Floor,
@@ -13,7 +13,7 @@ public enum CellKind
ControlTerminal
}
public enum PipeMedium
public enum EPipeMedium
{
None,
Pressure,
@@ -21,7 +21,7 @@ public enum PipeMedium
Fuel
}
public enum FailureKind
public enum EFailureKind
{
PipeBurst,
Ignition,
@@ -45,8 +45,7 @@ public sealed record HazardState
{
public HazardState Clamp()
{
return this with
{
return this with {
Heat = Rules.Clamp(Heat),
Smoke = Rules.Clamp(Smoke),
FuelVapor = Rules.Clamp(FuelVapor),
@@ -69,8 +68,8 @@ public sealed record HazardState
public sealed record CellState
{
public CellKind Kind { get; init; } = CellKind.Floor;
public PipeMedium Pipe { get; init; }
public ECellKind Kind { get; init; } = ECellKind.Floor;
public EPipeMedium Pipe { get; init; }
public int Flow { get; init; }
public int Pressure { get; init; }
public int Integrity { get; init; } = 10;
@@ -79,9 +78,8 @@ public sealed record CellState
public bool Powered { get; init; }
public bool DoorLocked { get; init; }
public HazardState Hazards { get; init; } = new();
public bool IsWalkable => Kind != CellKind.Wall && Kind != CellKind.Empty;
public bool HasPipe => Pipe != PipeMedium.None;
public bool IsWalkable => Kind != ECellKind.Wall && Kind != ECellKind.Empty;
public bool HasPipe => Pipe != EPipeMedium.None;
}
public sealed record GlobalState
@@ -97,7 +95,7 @@ public sealed record GlobalState
public string Status { get; init; } = "STABILIZE SYSTEMS";
}
public sealed record Forecast(FailureKind Kind, GridPosition? Position, int Turns, string Message);
public sealed record Forecast(EFailureKind Kind, GridPosition? Position, int Turns, string Message);
public sealed record LevelState
{
@@ -108,12 +106,15 @@ public sealed record LevelState
var cells = CreateCells(width, height);
for (var y = 0; y < height; y++)
for (var x = 0; x < width; x++)
if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
cells[y * width + x] = cells[y * width + x] with { Kind = CellKind.Wall };
return new()
{
for (var x = 0; x < width; x++)
{
if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
cells[y * width + x] = cells[y * width + x] with { Kind = ECellKind.Wall };
}
}
return new() {
Name = name,
Width = width,
Height = height,

View File

@@ -1,4 +1,4 @@
namespace ReactorMaintenance.Simulation;
namespace ReactorMaintenance.Simulation;
public sealed class SimulationEngine
{
@@ -7,52 +7,51 @@ public sealed class SimulationEngine
var cells = level.Cells.ToArray();
for (var y = 0; y < level.Height; y++)
for (var x = 0; x < level.Width; x++)
{
var position = new GridPosition(x, y);
var index = level.Index(position);
var cell = cells[index];
if (!cell.IsWalkable)
continue;
var hazards = ApplyPipeLeaks(cell);
hazards = ApplyMachineEffects(cell, hazards);
hazards = ApplyFireAndElectricalHazards(cell, hazards);
hazards = hazards.Clamp();
var integrity = cell.Integrity;
if (cell.HasPipe && cell.Pressure > 7)
integrity -= cell.Pressure - 7;
if (hazards.Heat >= 10 || hazards.Fire)
for (var x = 0; x < level.Width; x++)
{
integrity -= cell.HasPipe ? 1 : 0;
hazards = hazards with { Stability = hazards.Stability - 1 };
}
var position = new GridPosition(x, y);
var index = level.Index(position);
var cell = cells[index];
if (integrity <= 0 && cell.HasPipe)
{
cell = cell with
if (!cell.IsWalkable)
continue;
var hazards = ApplyPipeLeaks(cell);
hazards = ApplyMachineEffects(cell, hazards);
hazards = ApplyFireAndElectricalHazards(cell, hazards);
hazards = hazards.Clamp();
var integrity = cell.Integrity;
if (cell is { HasPipe: true, Pressure: > 7 })
integrity -= cell.Pressure - 7;
if (hazards.Heat >= 10 || hazards.Fire)
{
LeakRate = Math.Max(cell.LeakRate, 3),
Flow = 0,
PipeOpen = false
integrity -= cell.HasPipe ? 1 : 0;
hazards = hazards with { Stability = hazards.Stability - 1 };
}
if (integrity <= 0 && cell.HasPipe)
{
cell = cell with {
LeakRate = Math.Max(cell.LeakRate, 3),
Flow = 0,
PipeOpen = false
};
}
cells[index] = cell with {
Integrity = Rules.Clamp(integrity),
Hazards = hazards.Clamp()
};
}
cells[index] = cell with
{
Integrity = Rules.Clamp(integrity),
Hazards = hazards.Clamp()
};
}
cells = SpreadSmoke(level, cells);
var global = UpdateGlobal(level, cells);
var next = level with
{
var next = level with {
Cells = cells,
Global = global with { Turn = level.Global.Turn + 1 }
};
@@ -70,25 +69,25 @@ public sealed class SimulationEngine
var position = new GridPosition(x, y);
var cell = level.GetCell(position);
if (cell.HasPipe && cell.Pressure > 7 && cell.Integrity > 0)
if (cell is { HasPipe: true, Pressure: > 7, Integrity: > 0 })
{
var damagePerTurn = Math.Max(1, cell.Pressure - 7);
var turns = (int)Math.Ceiling(cell.Integrity / (double)damagePerTurn);
if (turns <= 4)
forecasts.Add(new(FailureKind.PipeBurst, position, turns, $"PIPE BURST PREDICTED AT {x},{y} IN {turns} TURNS"));
forecasts.Add(new(EFailureKind.PipeBurst, position, turns, $"PIPE BURST PREDICTED AT {x},{y} IN {turns} TURNS"));
}
var fuelLeakNearIgnition = cell.Pipe == PipeMedium.Fuel && cell.LeakRate > 0 && (cell.Pressure >= 7 || cell.Kind == CellKind.Generator);
var ignitionRisk = (cell.Hazards.FuelVapor >= 4 || cell.Hazards.LiquidFuel >= 6 || fuelLeakNearIgnition) && (cell.Hazards.Heat >= 8 || cell.Hazards.ElectricalCharge >= 4 || cell.Kind == CellKind.Generator);
var fuelLeakNearIgnition = cell is { Pipe: EPipeMedium.Fuel, LeakRate: > 0 } && (cell.Pressure >= 7 || cell.Kind == ECellKind.Generator);
var ignitionRisk = (cell.Hazards.FuelVapor >= 4 || cell.Hazards.LiquidFuel >= 6 || fuelLeakNearIgnition) && (cell.Hazards.Heat >= 8 || cell.Hazards.ElectricalCharge >= 4 || cell.Kind == ECellKind.Generator);
if (ignitionRisk && !cell.Hazards.Fire)
forecasts.Add(new(FailureKind.Ignition, position, 1, $"FUEL IGNITION PREDICTED AT {x},{y} NEXT TURN"));
forecasts.Add(new(EFailureKind.Ignition, position, 1, $"FUEL IGNITION PREDICTED AT {x},{y} NEXT TURN"));
}
if (level.Global.CoreHeat >= 8)
forecasts.Add(new(FailureKind.Meltdown, null, Math.Max(1, 11 - level.Global.CoreHeat), "CORE MELTDOWN APPROACHING"));
forecasts.Add(new(EFailureKind.Meltdown, null, Math.Max(1, 11 - level.Global.CoreHeat), "CORE MELTDOWN APPROACHING"));
if (IsReactorReady(level))
forecasts.Add(new(FailureKind.ReactorReady, null, 0, "REACTOR READY"));
forecasts.Add(new(EFailureKind.ReactorReady, null, 0, "REACTOR READY"));
return forecasts.OrderBy(f => f.Turns).ThenBy(f => f.Message).ToArray();
}
@@ -98,10 +97,8 @@ public sealed class SimulationEngine
if (!IsReactorReady(level))
return level with { Global = level.Global with { Status = "REACTOR NOT READY" } };
return level with
{
Global = level.Global with
{
return level with {
Global = level.Global with {
ReactorActivated = true,
Status = "REACTOR ONLINE"
}
@@ -114,32 +111,28 @@ public sealed class SimulationEngine
if (!cell.HasPipe || cell.LeakRate <= 0)
return hazards;
return cell.Pipe switch
{
PipeMedium.Fuel => hazards with
{
return cell.Pipe switch {
EPipeMedium.Fuel => hazards with {
LiquidFuel = hazards.LiquidFuel + cell.LeakRate,
FuelVapor = hazards.FuelVapor + (cell.Pressure >= 7 ? cell.LeakRate : Math.Max(0, hazards.Heat - 3) / 3)
},
PipeMedium.Coolant => hazards with
{
EPipeMedium.Coolant => hazards with {
CoolantPooling = hazards.CoolantPooling + cell.LeakRate,
Heat = hazards.Heat - Math.Max(1, cell.LeakRate / 2),
Smoke = hazards.Smoke + (hazards.Heat >= 7 ? 2 : 0)
},
PipeMedium.Pressure => hazards with { Smoke = hazards.Smoke + (cell.Pressure >= 8 ? 1 : 0) },
_ => hazards
EPipeMedium.Pressure => hazards with { Smoke = hazards.Smoke + (cell.Pressure >= 8 ? 1 : 0) },
_ => hazards
};
}
private static HazardState ApplyMachineEffects(CellState cell, HazardState hazards)
{
return cell.Kind switch
{
CellKind.Generator when cell.Powered => hazards with { Heat = hazards.Heat + 1 },
CellKind.CoolingPump when cell.Powered => hazards with { Heat = hazards.Heat - 2 },
CellKind.Reactor => hazards with { Heat = hazards.Heat + 1 },
_ => hazards
return cell.Kind switch {
ECellKind.Generator when cell.Powered => hazards with { Heat = hazards.Heat + 1 },
ECellKind.CoolingPump when cell.Powered => hazards with { Heat = hazards.Heat - 2 },
ECellKind.Reactor => hazards with { Heat = hazards.Heat + 1 },
_ => hazards
};
}
@@ -149,11 +142,10 @@ public sealed class SimulationEngine
hazards = hazards with { ElectricalCharge = hazards.ElectricalCharge + 2 };
var hasFuel = hazards.FuelVapor >= 4 || hazards.LiquidFuel >= 6;
var hasIgnition = hazards.Heat >= 8 || hazards.ElectricalCharge >= 4 || (cell.Kind == CellKind.Generator && cell.Powered);
var hasIgnition = hazards.Heat >= 8 || hazards.ElectricalCharge >= 4 || cell is { Kind: ECellKind.Generator, Powered: true };
if ((hasFuel && hasIgnition) || hazards.Fire)
{
hazards = hazards with
{
hazards = hazards with {
Fire = hasFuel || hazards.Fire,
Heat = hazards.Heat + 2,
Smoke = hazards.Smoke + 2,
@@ -171,20 +163,22 @@ public sealed class SimulationEngine
{
var next = cells.ToArray();
for (var y = 0; y < level.Height; y++)
for (var x = 0; x < level.Width; x++)
{
var position = new GridPosition(x, y);
var cell = cells[level.Index(position)];
if (cell.Hazards.Smoke < 6)
continue;
foreach (var neighbor in position.Neighbors().Where(level.InBounds))
for (var x = 0; x < level.Width; x++)
{
var neighborCell = next[level.Index(neighbor)];
if (!neighborCell.IsWalkable || neighborCell.DoorLocked)
var position = new GridPosition(x, y);
var cell = cells[level.Index(position)];
if (cell.Hazards.Smoke < 6)
continue;
next[level.Index(neighbor)] = neighborCell with { Hazards = neighborCell.Hazards with { Smoke = Rules.Clamp(neighborCell.Hazards.Smoke + 1) } };
foreach (var neighbor in position.Neighbors().Where(level.InBounds))
{
var neighborCell = next[level.Index(neighbor)];
if (!neighborCell.IsWalkable || neighborCell.DoorLocked)
continue;
next[level.Index(neighbor)] = neighborCell with { Hazards = neighborCell.Hazards with { Smoke = Rules.Clamp(neighborCell.Hazards.Smoke + 1) } };
}
}
}
@@ -193,18 +187,14 @@ public sealed class SimulationEngine
private static GlobalState UpdateGlobal(LevelState level, CellState[] cells)
{
var reactorHeat = cells.Where(c => c.Kind == CellKind.Reactor).Select(c => c.Hazards.Heat).DefaultIfEmpty(level.Global.CoreHeat).Max();
var poweredGenerators = cells.Count(c => c.Kind == CellKind.Generator && c.Powered && !c.Hazards.Fire);
var poweredPumps = cells.Count(c => c.Kind == CellKind.CoolingPump && c.Powered && !c.Hazards.Fire);
var damagedCriticalCells = cells.Count(c => c.Kind is CellKind.Reactor or CellKind.Generator or CellKind.CoolingPump && c.Hazards.Stability <= 3);
var reactorHeat = cells.Where(c => c.Kind == ECellKind.Reactor).Select(c => c.Hazards.Heat).DefaultIfEmpty(level.Global.CoreHeat).Max();
var poweredGenerators = cells.Count(c => c is { Kind: ECellKind.Generator, Powered: true, Hazards.Fire: false });
var poweredPumps = cells.Count(c => c is { Kind: ECellKind.CoolingPump, Powered: true, Hazards.Fire: false });
var damagedCriticalCells = cells.Count(c => c.Kind is ECellKind.Reactor or ECellKind.Generator or ECellKind.CoolingPump && c.Hazards.Stability <= 3);
var stability = Rules.Clamp(level.Global.FacilityStability - damagedCriticalCells);
var lost = reactorHeat >= 10 || stability <= 0;
var status = lost ? reactorHeat >= 10 ? "CORE MELTDOWN" : "FACILITY STABILITY COLLAPSE" : "STABILIZE SYSTEMS";
var global = level.Global with
{
var global = level.Global with {
CoreHeat = Rules.Clamp(reactorHeat - poweredPumps),
Power = Rules.Clamp(poweredGenerators * 3),
Cooling = Rules.Clamp(poweredPumps * 3),
@@ -213,20 +203,14 @@ public sealed class SimulationEngine
Status = status
};
return IsReactorReady(level with
{
Cells = cells,
Global = global
})
? global with { Status = "REACTOR READY" }
: global;
return IsReactorReady(level with { Cells = cells, Global = global }) ? global with { Status = "REACTOR READY" } : global;
}
private static bool IsReactorReady(LevelState level)
{
var hasReactor = level.Cells.Any(c => c.Kind == CellKind.Reactor);
var hasStablePower = level.Global.Power >= 3 || level.Cells.Any(c => c.Kind == CellKind.Generator && c.Powered && !c.Hazards.Fire);
var hasCooling = level.Global.Cooling >= 3 || level.Cells.Any(c => c.Kind == CellKind.CoolingPump && c.Powered && !c.Hazards.Fire);
var hasReactor = level.Cells.Any(c => c.Kind == ECellKind.Reactor);
var hasStablePower = level.Global.Power >= 3 || level.Cells.Any(c => c is { Kind: ECellKind.Generator, Powered: true, Hazards.Fire: false });
var hasCooling = level.Global.Cooling >= 3 || level.Cells.Any(c => c is { Kind: ECellKind.CoolingPump, Powered: true, Hazards.Fire: false });
var reactorStable = level.Global.CoreHeat < 8;
return hasReactor && hasStablePower && hasCooling && reactorStable && !level.Global.Lost;
}

View File

@@ -1,4 +1,4 @@
<Application
<Application
x:Class="ReactorMaintenance.Win2D.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

View File

@@ -1,8 +1,8 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml;
namespace ReactorMaintenance.Win2D;
public partial class App : Application
public partial class App
{
public App()
{
@@ -11,9 +11,9 @@ public partial class App : Application
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
_window = new MainWindow();
_window.Activate();
m_Window = new MainWindow();
m_Window.Activate();
}
private Window? _window;
private Window? m_Window;
}

View File

@@ -1,4 +1,4 @@
<Window
<Window
x:Class="ReactorMaintenance.Win2D.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

View File

@@ -1,4 +1,4 @@
using System.Numerics;
using System.Numerics;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Pickers;
@@ -11,11 +11,13 @@ using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using ReactorMaintenance.Simulation;
using System.Globalization;
using Windows.UI.Popups;
using WinRT.Interop;
namespace ReactorMaintenance.Win2D;
public sealed partial class MainWindow : Window
public sealed partial class MainWindow
{
private sealed record CanvasLayout(double CellSize, double OriginX, double OriginY)
{
@@ -29,95 +31,111 @@ public sealed partial class MainWindow : Window
{
InitializeComponent();
_level = BuildStarterLevel();
ToolPicker.ItemsSource = Enum.GetValues<EditorTool>();
ToolPicker.SelectedItem = _selectedTool;
m_Level = BuildStarterLevel();
ToolPicker.ItemsSource = Enum.GetValues<EEditorTool>();
ToolPicker.SelectedItem = m_SelectedTool;
RefreshInspector();
}
private void ToolPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ToolPicker.SelectedItem is EditorTool tool)
_selectedTool = tool;
if (ToolPicker.SelectedItem is EEditorTool tool)
m_SelectedTool = tool;
}
private void New_Click(object sender, RoutedEventArgs e)
{
_level = BuildStarterLevel();
_currentFile = null;
_selectedCell = null;
m_Level = BuildStarterLevel();
m_CurrentFile = null;
m_SelectedCell = null;
RefreshInspector();
LevelCanvas.Invalidate();
}
private async void Open_Click(object sender, RoutedEventArgs e)
private async void Open_Click(object sender, RoutedEventArgs args)
{
var picker = new FileOpenPicker();
InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(this));
picker.FileTypeFilter.Add(".json");
var file = await picker.PickSingleFileAsync();
if (file is null)
return;
var json = await FileIO.ReadTextAsync(file);
_level = LevelSerializer.Deserialize(json);
_level = _level with { Forecasts = _simulation.Forecast(_level) };
_currentFile = file;
_selectedCell = null;
RefreshInspector();
LevelCanvas.Invalidate();
}
private async void Save_Click(object sender, RoutedEventArgs e)
{
var file = _currentFile;
if (file is null)
try
{
var picker = new FileSavePicker();
var picker = new FileOpenPicker();
InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(this));
picker.SuggestedFileName = _level.Name.Replace(' ', '-').ToLowerInvariant();
picker.FileTypeChoices.Add("Reactor level", new List<string> { ".json" });
file = await picker.PickSaveFileAsync();
picker.FileTypeFilter.Add(".json");
var file = await picker.PickSingleFileAsync();
if (file is null)
return;
var json = await FileIO.ReadTextAsync(file);
m_Level = LevelSerializer.Deserialize(json);
m_Level = m_Level with { Forecasts = m_Simulation.Forecast(m_Level) };
m_CurrentFile = file;
m_SelectedCell = null;
RefreshInspector();
LevelCanvas.Invalidate();
}
catch (Exception e)
{
var messageDialog = new MessageDialog(e.Message);
_ = await messageDialog.ShowAsync();
}
}
if (file is null)
return;
private async void Save_Click(object sender, RoutedEventArgs args)
{
try
{
var file = m_CurrentFile;
if (file is null)
{
var picker = new FileSavePicker();
InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(this));
picker.SuggestedFileName = m_Level.Name.Replace(' ', '-').ToLowerInvariant();
picker.FileTypeChoices.Add("Reactor level", [".json"]);
file = await picker.PickSaveFileAsync();
}
await FileIO.WriteTextAsync(file, LevelSerializer.Serialize(_level));
_currentFile = file;
if (file is null)
return;
await FileIO.WriteTextAsync(file, LevelSerializer.Serialize(m_Level));
m_CurrentFile = file;
}
catch (Exception e)
{
var messageDialog = new MessageDialog(e.Message);
_ = await messageDialog.ShowAsync();
}
}
private void Simulate_Click(object sender, RoutedEventArgs e)
{
_level = _simulation.AdvanceTurn(_level);
m_Level = m_Simulation.AdvanceTurn(m_Level);
RefreshInspector();
LevelCanvas.Invalidate();
}
private void Activate_Click(object sender, RoutedEventArgs e)
{
_level = _simulation.ActivateReactor(_level);
m_Level = m_Simulation.ActivateReactor(m_Level);
RefreshInspector();
LevelCanvas.Invalidate();
}
private void LevelCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)
{
_painting = true;
LevelCanvas.CapturePointer(e.Pointer);
m_Painting = true;
_ = LevelCanvas.CapturePointer(e.Pointer);
PaintAt(e.GetCurrentPoint(LevelCanvas).Position);
}
private void LevelCanvas_PointerMoved(object sender, PointerRoutedEventArgs e)
{
if (_painting)
if (m_Painting)
PaintAt(e.GetCurrentPoint(LevelCanvas).Position);
}
private void LevelCanvas_PointerReleased(object sender, PointerRoutedEventArgs e)
{
_painting = false;
m_Painting = false;
LevelCanvas.ReleasePointerCapture(e.Pointer);
}
@@ -126,9 +144,9 @@ public sealed partial class MainWindow : Window
if (!TryGetGridPosition(point, out var position))
return;
_selectedCell = position;
_level = LevelEditor.Apply(_level, position, _selectedTool);
_level = _level with { Forecasts = _simulation.Forecast(_level) };
m_SelectedCell = position;
m_Level = LevelEditor.Apply(m_Level, position, m_SelectedTool);
m_Level = m_Level with { Forecasts = m_Simulation.Forecast(m_Level) };
RefreshInspector();
LevelCanvas.Invalidate();
}
@@ -146,11 +164,11 @@ public sealed partial class MainWindow : Window
private void DrawCells(CanvasDrawingSession drawing, CanvasLayout layout)
{
for (var y = 0; y < _level.Height; y++)
for (var x = 0; x < _level.Width; x++)
for (var y = 0; y < m_Level.Height; y++)
for (var x = 0; x < m_Level.Width; x++)
{
var position = new GridPosition(x, y);
var cell = _level.GetCell(position);
var cell = m_Level.GetCell(position);
var rect = layout.CellRect(x, y);
drawing.FillRectangle(rect, CellColor(cell));
@@ -158,15 +176,14 @@ public sealed partial class MainWindow : Window
if (cell.HasPipe)
{
var center = new Vector2((float)(rect.X + rect.Width / 2), (float)(rect.Y + rect.Height / 2));
var pipeColor = cell.Pipe switch
{
PipeMedium.Coolant => Colors.DeepSkyBlue,
PipeMedium.Fuel => Colors.Goldenrod,
PipeMedium.Pressure => Colors.LightSteelBlue,
_ => Colors.Transparent
var pipeColor = cell.Pipe switch {
EPipeMedium.Coolant => Colors.DeepSkyBlue,
EPipeMedium.Fuel => Colors.Goldenrod,
EPipeMedium.Pressure => Colors.LightSteelBlue,
_ => Colors.Transparent
};
drawing.DrawLine(new((float)rect.X + 6, center.Y), new((float)(rect.X + rect.Width - 6), center.Y), pipeColor, Math.Max(3, (float)rect.Width / 7));
drawing.DrawLine(new(center.X, (float)rect.Y + 6), new(center.X, (float)(rect.Y + rect.Height - 6)), pipeColor, Math.Max(3, (float)rect.Width / 7));
drawing.DrawLine(center with { X = (float)rect.X + 6 }, center with { X = (float)(rect.X + rect.Width - 6) }, pipeColor, Math.Max(3, (float)rect.Width / 7));
drawing.DrawLine(center with { Y = (float)rect.Y + 6 }, center with { Y = (float)(rect.Y + rect.Height - 6) }, pipeColor, Math.Max(3, (float)rect.Width / 7));
}
if (cell.LeakRate > 0)
@@ -175,7 +192,7 @@ public sealed partial class MainWindow : Window
if (cell.Hazards.Fire)
drawing.FillCircle(new((float)(rect.X + rect.Width * 0.5), (float)(rect.Y + rect.Height * 0.5)), (float)rect.Width * 0.24f, Colors.OrangeRed);
if (_selectedCell == position)
if (m_SelectedCell == position)
drawing.DrawRectangle(rect, Colors.White, 3);
DrawCellGlyph(drawing, cell, rect);
@@ -184,48 +201,45 @@ public sealed partial class MainWindow : Window
private void DrawCellGlyph(CanvasDrawingSession drawing, CellState cell, Rect rect)
{
var text = cell.Kind switch
{
CellKind.Reactor => "R",
CellKind.CoolingPump => "C",
CellKind.Generator => "G",
CellKind.PressureRegulator => "P",
CellKind.DiagnosticTerminal => "D",
CellKind.ControlTerminal => "T",
_ => string.Empty
var text = cell.Kind switch {
ECellKind.Reactor => "R",
ECellKind.CoolingPump => "C",
ECellKind.Generator => "G",
ECellKind.PressureRegulator => "P",
ECellKind.DiagnosticTerminal => "D",
ECellKind.ControlTerminal => "T",
_ => string.Empty
};
if (string.IsNullOrEmpty(text))
return;
using var format = new CanvasTextFormat
{
FontSize = Math.Max(14, (float)rect.Width * 0.42f),
HorizontalAlignment = CanvasHorizontalAlignment.Center,
VerticalAlignment = CanvasVerticalAlignment.Center
};
using var format = new CanvasTextFormat();
format.FontSize = Math.Max(14, (float)rect.Width * 0.42f);
format.HorizontalAlignment = CanvasHorizontalAlignment.Center;
format.VerticalAlignment = CanvasVerticalAlignment.Center;
drawing.DrawText(text, rect, Colors.White, format);
}
private void DrawGrid(CanvasDrawingSession drawing, CanvasLayout layout)
{
for (var x = 0; x <= _level.Width; x++)
for (var x = 0; x <= m_Level.Width; x++)
{
var xPos = (float)(layout.OriginX + x * layout.CellSize);
drawing.DrawLine(xPos, (float)layout.OriginY, xPos, (float)(layout.OriginY + _level.Height * layout.CellSize), ColorHelper.FromArgb(120, 91, 104, 115), 1);
drawing.DrawLine(xPos, (float)layout.OriginY, xPos, (float)(layout.OriginY + m_Level.Height * layout.CellSize), ColorHelper.FromArgb(120, 91, 104, 115), 1);
}
for (var y = 0; y <= _level.Height; y++)
for (var y = 0; y <= m_Level.Height; y++)
{
var yPos = (float)(layout.OriginY + y * layout.CellSize);
drawing.DrawLine((float)layout.OriginX, yPos, (float)(layout.OriginX + _level.Width * layout.CellSize), yPos, ColorHelper.FromArgb(120, 91, 104, 115), 1);
drawing.DrawLine((float)layout.OriginX, yPos, (float)(layout.OriginX + m_Level.Width * layout.CellSize), yPos, ColorHelper.FromArgb(120, 91, 104, 115), 1);
}
}
private void DrawRobot(CanvasDrawingSession drawing, CanvasLayout layout)
{
var rect = layout.CellRect(_level.Robot.X, _level.Robot.Y);
var rect = layout.CellRect(m_Level.Robot.X, m_Level.Robot.Y);
var center = new Vector2((float)(rect.X + rect.Width / 2), (float)(rect.Y + rect.Height / 2));
drawing.FillCircle(center, (float)rect.Width * 0.28f, Colors.White);
drawing.DrawCircle(center, (float)rect.Width * 0.28f, Colors.Black, 2);
@@ -237,123 +251,113 @@ public sealed partial class MainWindow : Window
var x = (int)((point.X - layout.OriginX) / layout.CellSize);
var y = (int)((point.Y - layout.OriginY) / layout.CellSize);
position = new(x, y);
return _level.InBounds(position);
return m_Level.InBounds(position);
}
private CanvasLayout GetLayout()
{
var availableWidth = Math.Max(1, LevelCanvas.ActualWidth);
var availableHeight = Math.Max(1, LevelCanvas.ActualHeight);
var size = Math.Floor(Math.Min(availableWidth / _level.Width, availableHeight / _level.Height));
var size = Math.Floor(Math.Min(availableWidth / m_Level.Width, availableHeight / m_Level.Height));
size = Math.Max(20, size);
var originX = Math.Max(0, (availableWidth - size * _level.Width) / 2);
var originY = Math.Max(0, (availableHeight - size * _level.Height) / 2);
var originX = Math.Max(0, (availableWidth - size * m_Level.Width) / 2);
var originY = Math.Max(0, (availableHeight - size * m_Level.Height) / 2);
return new(size, originX, originY);
}
private static Color CellColor(CellState cell)
{
if (cell.Kind == CellKind.Wall)
if (cell.Kind == ECellKind.Wall)
return ColorHelper.FromArgb(255, 54, 61, 68);
if (cell.Hazards.Fire)
return ColorHelper.FromArgb(255, 91, 39, 30);
return cell.Kind switch
{
CellKind.Reactor => ColorHelper.FromArgb(255, 61, 76, 82),
CellKind.CoolingPump => ColorHelper.FromArgb(255, 25, 79, 96),
CellKind.Generator => ColorHelper.FromArgb(255, 86, 75, 35),
CellKind.PressureRegulator => ColorHelper.FromArgb(255, 70, 78, 98),
CellKind.DiagnosticTerminal => ColorHelper.FromArgb(255, 39, 84, 62),
CellKind.ControlTerminal => ColorHelper.FromArgb(255, 80, 61, 91),
_ => ColorHelper.FromArgb(255, 31, 36, 40)
return cell.Kind switch {
ECellKind.Reactor => ColorHelper.FromArgb(255, 61, 76, 82),
ECellKind.CoolingPump => ColorHelper.FromArgb(255, 25, 79, 96),
ECellKind.Generator => ColorHelper.FromArgb(255, 86, 75, 35),
ECellKind.PressureRegulator => ColorHelper.FromArgb(255, 70, 78, 98),
ECellKind.DiagnosticTerminal => ColorHelper.FromArgb(255, 39, 84, 62),
ECellKind.ControlTerminal => ColorHelper.FromArgb(255, 80, 61, 91),
_ => ColorHelper.FromArgb(255, 31, 36, 40)
};
}
private void RefreshInspector()
{
LevelNameText.Text = _level.Name;
TurnText.Text = _level.Global.Turn.ToString();
StatusText.Text = _level.Global.Status;
GlobalText.Text = $"Power: {_level.Global.Power}/10\n" + $"Cooling: {_level.Global.Cooling}/10\n" + $"Core Heat: {_level.Global.CoreHeat}/10\n" + $"Facility Stability: {_level.Global.FacilityStability}/10";
LevelNameText.Text = m_Level.Name;
TurnText.Text = m_Level.Global.Turn.ToString(CultureInfo.InvariantCulture);
StatusText.Text = m_Level.Global.Status;
GlobalText.Text = $"Power: {m_Level.Global.Power}/10\n" + $"Cooling: {m_Level.Global.Cooling}/10\n" + $"Core Heat: {m_Level.Global.CoreHeat}/10\n" + $"Facility Stability: {m_Level.Global.FacilityStability}/10";
if (_selectedCell is { } position && _level.InBounds(position))
if (m_SelectedCell is { } position && m_Level.InBounds(position))
{
var cell = _level.GetCell(position);
var cell = m_Level.GetCell(position);
CellText.Text = $"Position: {position.X},{position.Y}\n" + $"Kind: {cell.Kind}\n" + $"Pipe: {cell.Pipe}\n" + $"Flow: {cell.Flow}, Pressure: {cell.Pressure}\n" + $"Integrity: {cell.Integrity}, Leak: {cell.LeakRate}\n" + $"Heat: {cell.Hazards.Heat}, Smoke: {cell.Hazards.Smoke}\n" + $"Fuel Vapor: {cell.Hazards.FuelVapor}, Fuel: {cell.Hazards.LiquidFuel}\n" + $"Coolant: {cell.Hazards.CoolantPooling}, Charge: {cell.Hazards.ElectricalCharge}";
}
else
CellText.Text = "No cell selected.";
ForecastList.ItemsSource = _level.Forecasts;
ForecastList.ItemsSource = m_Level.Forecasts;
}
private static LevelState BuildStarterLevel()
{
var level = LevelState.Create("Cooling Sector B", 16, 12);
level = level.SetCell(new(3, 5), new()
{
Kind = CellKind.CoolingPump,
Pipe = PipeMedium.Coolant,
level = level.SetCell(new(3, 5), new() {
Kind = ECellKind.CoolingPump,
Pipe = EPipeMedium.Coolant,
Flow = 5,
Pressure = 5,
Powered = true
});
level = level.SetCell(new(4, 5), new()
{
Pipe = PipeMedium.Coolant,
level = level.SetCell(new(4, 5), new() {
Pipe = EPipeMedium.Coolant,
Flow = 5,
Pressure = 7
});
level = level.SetCell(new(5, 5), new()
{
Pipe = PipeMedium.Coolant,
level = level.SetCell(new(5, 5), new() {
Pipe = EPipeMedium.Coolant,
Flow = 3,
Pressure = 8,
LeakRate = 2,
Integrity = 4
});
level = level.SetCell(new(6, 5), new()
{
Pipe = PipeMedium.Coolant,
level = level.SetCell(new(6, 5), new() {
Pipe = EPipeMedium.Coolant,
Flow = 3,
Pressure = 7
});
level = level.SetCell(new(8, 5), new()
{
Kind = CellKind.Reactor,
Hazards = new()
{
level = level.SetCell(new(8, 5), new() {
Kind = ECellKind.Reactor,
Hazards = new() {
Heat = 6,
Stability = 8
}
});
level = level.SetCell(new(2, 8), new()
{
Kind = CellKind.Generator,
Pipe = PipeMedium.Fuel,
level = level.SetCell(new(2, 8), new() {
Kind = ECellKind.Generator,
Pipe = EPipeMedium.Fuel,
Flow = 4,
Pressure = 6,
Powered = true
});
level = level.SetCell(new(11, 4), new()
{
Kind = CellKind.DiagnosticTerminal,
level = level.SetCell(new(11, 4), new() {
Kind = ECellKind.DiagnosticTerminal,
Powered = true
});
level = level.SetCell(new(12, 8), new()
{
Kind = CellKind.ControlTerminal,
level = level.SetCell(new(12, 8), new() {
Kind = ECellKind.ControlTerminal,
Powered = true
});
return level with { Forecasts = new SimulationEngine().Forecast(level) };
}
private readonly SimulationEngine _simulation = new();
private StorageFile? _currentFile;
private LevelState _level;
private bool _painting;
private GridPosition? _selectedCell;
private EditorTool _selectedTool = EditorTool.Floor;
private readonly SimulationEngine m_Simulation = new();
private StorageFile? m_CurrentFile;
private LevelState m_Level;
private bool m_Painting;
private GridPosition? m_SelectedCell;
private EEditorTool m_SelectedTool = EEditorTool.Floor;
}

View File

@@ -1,26 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<RootNamespace>ReactorMaintenance.Win2D</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Platforms>x86;x64;arm64</Platforms>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64</RuntimeIdentifiers>
<UseWinUI>true</UseWinUI>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
</PropertyGroup>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<RootNamespace>ReactorMaintenance.Win2D</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Platforms>x86;x64;arm64</Platforms>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64</RuntimeIdentifiers>
<UseWinUI>true</UseWinUI>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Graphics.Win2D" Version="1.4.0" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.28000.1839" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.8.260317003" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Graphics.Win2D" Version="1.4.0" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.28000.1839" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.8.260317003" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ReactorMaintenance.Simulation\ReactorMaintenance.Simulation.csproj" />
</ItemGroup>
</Project>
<ItemGroup>
<ProjectReference Include="..\ReactorMaintenance.Simulation\ReactorMaintenance.Simulation.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="ReactorMaintenance.Win2D.app"/>
<application xmlns="urn:schemas-microsoft-com:asm.v3">