main init
This commit is contained in:
42
launcher/Launcher.csproj
Normal file
42
launcher/Launcher.csproj
Normal file
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Robot Clash desktop window: shows the HTML game in WebView2. game\** is embedded as
|
||||
resources (game/...) and served from https://robotclash.game/ - one exe, nothing unpacked.
|
||||
Build with ..\build.ps1. From _Tools\Library\web\template. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>RobotClash</AssemblyName>
|
||||
<RootNamespace>RobotClash</RootNamespace>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Product>Robot Clash</Product>
|
||||
<Company>Michael Media</Company>
|
||||
<Copyright>(c) 2026 Michael Media</Copyright>
|
||||
<Version>1.0.0</Version>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<DebugType>none</DebugType>
|
||||
<SatelliteResourceLanguages>de</SatelliteResourceLanguages>
|
||||
<NoWarn>$(NoWarn);MSB3277</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- build.ps1 creates app.ico from game\assets\Sprites\icon.png -->
|
||||
<PropertyGroup Condition="Exists('app.ico')">
|
||||
<ApplicationIcon>app.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="..\game\**\*.*" LogicalName="game/%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
175
launcher/Program.cs
Normal file
175
launcher/Program.cs
Normal file
@@ -0,0 +1,175 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.WinForms;
|
||||
|
||||
namespace RobotClash;
|
||||
|
||||
static class Program
|
||||
{
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new MainForm());
|
||||
}
|
||||
}
|
||||
|
||||
// One borderless window with WebView2. The game files are embedded resources ("game/<path>")
|
||||
// and answered from https://robotclash.game/<path> via WebResourceRequested.
|
||||
// localStorage (saves, settings) lives in %LOCALAPPDATA%\RobotClash\WebView2.
|
||||
// The page talks to the window with chrome.webview.postMessage("maximize"|"minimize"|"quit"|"drag")
|
||||
// - see kit-host.js. From _Tools\Library\web\template.
|
||||
sealed class MainForm : Form
|
||||
{
|
||||
const string AppName = "Robot Clash";
|
||||
const string Host = "https://robotclash.game/";
|
||||
const double Aspect = 16.0 / 10.0; // start window width / height
|
||||
const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
|
||||
static readonly string DataDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RobotClash");
|
||||
|
||||
readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false, DefaultBackgroundColor = Color.FromArgb(11, 15, 26) };
|
||||
readonly Label status = new()
|
||||
{
|
||||
Dock = DockStyle.Fill,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
Font = new Font("Segoe UI", 12f),
|
||||
ForeColor = Color.FromArgb(160, 160, 160),
|
||||
Text = $"Starte {AppName} …",
|
||||
};
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ReleaseCapture();
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
||||
const int WM_NCLBUTTONDOWN = 0xA1, HTCAPTION = 2;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
Text = AppName;
|
||||
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
|
||||
BackColor = Color.FromArgb(11, 15, 26);
|
||||
FormBorderStyle = FormBorderStyle.None; // the page draws its own window buttons
|
||||
// Start large: 88 % of the screen height, centred on the screen with the mouse.
|
||||
var wa = Screen.FromPoint(Cursor.Position).WorkingArea;
|
||||
int h = (int)(wa.Height * 0.88);
|
||||
int w = Math.Min((int)(h * Aspect), (int)(wa.Width * 0.92));
|
||||
StartPosition = FormStartPosition.Manual;
|
||||
Bounds = new Rectangle(wa.X + (wa.Width - w) / 2, wa.Y + (wa.Height - h) / 2, w, h);
|
||||
KeyPreview = true;
|
||||
Controls.Add(web);
|
||||
Controls.Add(status);
|
||||
Shown += async (_, _) => await StartAsync();
|
||||
}
|
||||
|
||||
async Task StartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(DataDir);
|
||||
var args = "--autoplay-policy=no-user-gesture-required";
|
||||
// GAME_DEBUG_PORT=9333 opens the DevTools protocol (automated tests)
|
||||
if (int.TryParse(Environment.GetEnvironmentVariable("GAME_DEBUG_PORT"), out var dbg))
|
||||
args += $" --remote-debugging-port={dbg}";
|
||||
var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"),
|
||||
new CoreWebView2EnvironmentOptions(args));
|
||||
await web.EnsureCoreWebView2Async(env);
|
||||
var core = web.CoreWebView2;
|
||||
core.Settings.IsStatusBarEnabled = false;
|
||||
core.Settings.AreDefaultContextMenusEnabled = false;
|
||||
core.Settings.IsZoomControlEnabled = false;
|
||||
core.Settings.AreBrowserAcceleratorKeysEnabled = false;
|
||||
#if DEBUG
|
||||
core.Settings.AreDevToolsEnabled = true;
|
||||
#else
|
||||
core.Settings.AreDevToolsEnabled = false;
|
||||
#endif
|
||||
core.AddWebResourceRequestedFilter(Host + "*", CoreWebView2WebResourceContext.All);
|
||||
core.WebResourceRequested += (_, e) => e.Response = Serve(core.Environment, e.Request.Uri);
|
||||
// links with target=_blank open in the normal browser
|
||||
core.NewWindowRequested += (_, e) =>
|
||||
{
|
||||
e.Handled = true;
|
||||
if (e.Uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||
try { Process.Start(new ProcessStartInfo(e.Uri) { UseShellExecute = true }); } catch { }
|
||||
};
|
||||
core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Host)) e.Cancel = true; };
|
||||
core.WebMessageReceived += (_, e) =>
|
||||
{
|
||||
switch (e.TryGetWebMessageAsString())
|
||||
{
|
||||
case "maximize": ToggleFullscreen(); break;
|
||||
case "minimize": WindowState = FormWindowState.Minimized; break;
|
||||
case "quit": Close(); break;
|
||||
case "drag":
|
||||
if (WindowState == FormWindowState.Normal && (MouseButtons & MouseButtons.Left) != 0)
|
||||
{
|
||||
ReleaseCapture();
|
||||
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, IntPtr.Zero);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
web.Source = new Uri(Host + "index.html");
|
||||
web.Visible = true;
|
||||
status.Visible = false;
|
||||
}
|
||||
catch (WebView2RuntimeNotFoundException)
|
||||
{
|
||||
status.Text = $"Es fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken zum Herunterladen, danach {AppName} neu starten.";
|
||||
status.Cursor = Cursors.Hand;
|
||||
status.Click += (_, _) => { try { Process.Start(new ProcessStartInfo(WebView2Download) { UseShellExecute = true }); } catch { } };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
status.Text = $"{AppName} konnte nicht starten:\n\n" + ex.Message;
|
||||
status.ForeColor = Color.FromArgb(220, 60, 60);
|
||||
}
|
||||
}
|
||||
|
||||
// Resource names from %(RecursiveDir) contain backslashes - map "game/a/b.png" -> real name.
|
||||
static readonly Dictionary<string, string> Resources = Assembly.GetExecutingAssembly()
|
||||
.GetManifestResourceNames()
|
||||
.ToDictionary(n => n.Replace('\\', '/'), n => n, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
static CoreWebView2WebResourceResponse Serve(CoreWebView2Environment env, string uri)
|
||||
{
|
||||
var path = Uri.UnescapeDataString(new Uri(uri).AbsolutePath.TrimStart('/'));
|
||||
if (path.Length == 0) path = "index.html";
|
||||
var stream = Resources.TryGetValue("game/" + path, out var name)
|
||||
? Assembly.GetExecutingAssembly().GetManifestResourceStream(name) : null;
|
||||
if (stream == null) return env.CreateWebResourceResponse(null, 404, "Not Found", "");
|
||||
var mem = new MemoryStream();
|
||||
stream.CopyTo(mem);
|
||||
mem.Position = 0;
|
||||
return env.CreateWebResourceResponse(mem, 200, "OK",
|
||||
$"Content-Type: {Mime(path)}\nContent-Length: {mem.Length}\nCache-Control: no-cache");
|
||||
}
|
||||
|
||||
static string Mime(string path) => Path.GetExtension(path).ToLowerInvariant() switch
|
||||
{
|
||||
".html" => "text/html; charset=utf-8",
|
||||
".js" or ".mjs" => "text/javascript",
|
||||
".css" => "text/css",
|
||||
".json" => "application/json",
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".webp" => "image/webp",
|
||||
".svg" => "image/svg+xml",
|
||||
".mp3" => "audio/mpeg",
|
||||
".ogg" => "audio/ogg",
|
||||
".wav" => "audio/wav",
|
||||
".ttf" => "font/ttf",
|
||||
".otf" => "font/otf",
|
||||
".woff2" => "font/woff2",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
|
||||
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
|
||||
{
|
||||
if (keyData == Keys.F11 || keyData == (Keys.Alt | Keys.Enter)) { ToggleFullscreen(); return true; }
|
||||
return base.ProcessCmdKey(ref msg, keyData);
|
||||
}
|
||||
|
||||
// Borderless window: maximised = covers the whole screen incl. taskbar.
|
||||
void ToggleFullscreen() =>
|
||||
WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized;
|
||||
}
|
||||
Reference in New Issue
Block a user