Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maui UI #19

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions BlazorClient/BlazorClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Blazor.Extensions.Canvas" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.3" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SharedTypes\SharedTypes.csproj" />
<ProjectReference Include="..\BlazorUI\BlazorUI.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
12 changes: 2 additions & 10 deletions BlazorClient/Pages/Play.razor
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
@page "/Play"
@using Blazor.Extensions
@using Blazor.Extensions.Canvas
@using Blazor.Extensions.Canvas.Canvas2D
@using Microsoft.AspNetCore.SignalR.Client

@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject ILogger<Play> Logger
@using Snakes.BlazorUI

<PageTitle>Sneks!</PageTitle>

<div id="canvasContainer" style="position: fixed; opacity: 1; background-color: black; width: 100%; height: 100%">
<BECanvas @ref="_canvas"></BECanvas>
</div>
<SnakeCanvas></SnakeCanvas>
2 changes: 2 additions & 0 deletions BlazorClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Snakes.BlazorUI;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<GameJsInterop>();
await builder.Build().RunAsync();
24 changes: 24 additions & 0 deletions BlazorUI/BlazorUI.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Snakes.BlazorUI</RootNamespace>
</PropertyGroup>

<ItemGroup>
<SupportedPlatform Include="browser" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="6.0.3" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.3" />
<PackageReference Include="Blazor.Extensions.Canvas" Version="1.1.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SharedTypes\SharedTypes.csproj" />
</ItemGroup>

</Project>
42 changes: 42 additions & 0 deletions BlazorUI/GameJsInterop.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Microsoft.JSInterop;

namespace Snakes.BlazorUI;

public class GameJsInterop : IAsyncDisposable
{
private readonly Lazy<Task<IJSObjectReference>> _moduleTask;
private DotNetObjectReference<SnakeCanvas>? _instanceRef;

public GameJsInterop(IJSRuntime jsRuntime)
{
_moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./_content/BlazorUI/GameJsInterop.js").AsTask());
}

public async ValueTask InitializeGame(SnakeCanvas instance)
{
var module = await _moduleTask.Value;
_instanceRef = DotNetObjectReference.Create(instance);
await module.InvokeAsync<object>("initGame", _instanceRef);
}

public async ValueTask<string> Prompt(string message)
{
var module = await _moduleTask.Value;
return await module.InvokeAsync<string>("showPrompt", message);
}

public async ValueTask DisposeAsync()
{
if (_instanceRef is not null)
{
_instanceRef.Dispose();
}

if (_moduleTask.IsValueCreated)
{
var module = await _moduleTask.Value;
await module.DisposeAsync();
}
}
}
9 changes: 9 additions & 0 deletions BlazorUI/SnakeCanvas.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@inject NavigationManager NavigationManager
@inject ILogger<SnakeCanvas> Logger
@inject GameJsInterop GameJsInterop
@inject HttpClient HttpClient

<div id="canvasContainer" style="position: fixed; opacity: 1; background-color: black; width: 100%; height: 100%">
<BECanvas @ref="_canvas"></BECanvas>
</div>

21 changes: 12 additions & 9 deletions BlazorClient/Pages/Play.razor.cs → BlazorUI/SnakeCanvas.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
using Blazor.Extensions.Canvas.Canvas2D;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;

namespace Snakes.Client.Pages;
namespace Snakes.BlazorUI;

public partial class Play : IAsyncDisposable
public partial class SnakeCanvas : IAsyncDisposable
{
private readonly string _playerName = "Pilchie";

BECanvas? _canvas;
Canvas2DContext? _context;
HubConnection? _hubConnection;

private string? _playerName;
private LobbyState _lobbyState = new(0, 5, new Size(96, 24));
private GameState _gameState;
private bool _alive = true;
Expand All @@ -36,9 +36,9 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
return;
}
_context = await _canvas.CreateCanvas2DAsync();
await JSRuntime.InvokeAsync<object>("initGame", DotNetObjectReference.Create(this));
await GameJsInterop.InitializeGame(this);

var hubUrl = NavigationManager.ToAbsoluteUri("/snakehub");
var hubUrl = HttpClient?.BaseAddress?.AbsoluteUri + "snakehub";
_hubConnection = new HubConnectionBuilder()
.WithUrl(hubUrl)
.WithAutomaticReconnect()
Expand Down Expand Up @@ -89,12 +89,15 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

_hubConnection.On<string>("OnDied", id => _alive = false);
_hubConnection.On<string, int>("OnScoreChanged", (id, newScore) => _score = newScore);

_playerName = await GameJsInterop.Prompt("What's your name?");

await _hubConnection.StartAsync();

_gameState = await _hubConnection.InvokeAsync<GameState>("GetCurrentState");
if (_gameState == GameState.NoGame)
{
await _hubConnection.InvokeAsync("InitializeNewGame", _lobbyState.BoardSize, _lobbyState.ExpectedPlayers); ;
await _hubConnection.InvokeAsync("InitializeNewGame", _lobbyState.BoardSize, _lobbyState.ExpectedPlayers);
}
else if (_gameState == GameState.Lobby)
{
Expand Down Expand Up @@ -328,14 +331,14 @@ public async Task OnKeyDown(int keyCode)
}

[JSInvokable]
public void OnResize(int width, int height)
public async Task OnResize(int width, int height)
{
_width = width;
_height = height;
}

[JSInvokable]
public void OnMouseMove(int mouseX, int mouseY)
public async Task OnMouseMove(int mouseX, int mouseY)
{
_mouseCoords = new Point(mouseX, mouseY);
}
Expand Down
7 changes: 7 additions & 0 deletions BlazorUI/_Imports.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@using Blazor.Extensions
@using Blazor.Extensions.Canvas
@using Blazor.Extensions.Canvas.Canvas2D
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.Extensions.Logging
@using Microsoft.JSInterop
@using Microsoft.AspNetCore.SignalR.Client
49 changes: 49 additions & 0 deletions BlazorUI/wwwroot/GameJsInterop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export function showPrompt(message) {
return prompt(message, '');
}

async function gameLoop(timeStamp) {
window.requestAnimationFrame(gameLoop);
await game.instance.invokeMethodAsync('GameLoop');
}

async function onKeyDown(e) {
await game.instance.invokeMethodAsync('OnKeyDown', e.keyCode);
}

async function onMouseDown(e) {
await game.instance.invokeMethodAsync('OnMouseDown', e.button);
}

async function onMouseMove(e) {
await game.instance.invokeMethodAsync('OnMouseMove', e.clientX, e.clientY);
}

async function onResize() {
if (!window.game.canvas)
return;

game.canvas.width = window.innerWidth;
game.canvas.height = window.innerHeight;

await game.instance.invokeMethodAsync('OnResize', window.innerWidth, window.innerHeight)
}

export function initGame(instance) {
var canvasContainer = document.getElementById('canvasContainer'),
canvases = canvasContainer.getElementsByTagName('canvas') || [];
window.game = {
instance: instance,
canvas: canvases.length ? canvases[0] : null
};

window.addEventListener("keydown", onKeyDown)
window.addEventListener("mousedown", onMouseDown);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("resize", onResize);

// Call once to set initial state.
onResize();

window.requestAnimationFrame(gameLoop);
};
2 changes: 1 addition & 1 deletion ConsoleSnake/ConsoleSnake.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.3" />
<PackageReference Include="Spectre.Console" Version="0.43.0" />
</ItemGroup>

Expand Down
1 change: 1 addition & 0 deletions HubAndHost/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ WORKDIR /src
COPY ["HubAndHost/HubAndHost.csproj", "HubAndHost/"]
COPY ["GrainInterfaces/GrainInterfaces.csproj", "GrainInterfaces/"]
COPY ["SharedTypes/SharedTypes.csproj", "SharedTypes/"]
COPY ["BlazorUI/BlazorUI.csproj", "BlazorUI/"]
COPY ["BlazorClient/BlazorClient.csproj", "BlazorClient/"]
COPY ["ConsoleSnake/ConsoleSnake.csproj", "ConsoleSnake/"]
RUN dotnet restore "ConsoleSnake/ConsoleSnake.csproj"
Expand Down
2 changes: 1 addition & 1 deletion HubAndHost/HubAndHost.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="6.0.3" />
<PackageReference Include="Microsoft.Orleans.Client" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.Clustering.AzureStorage" Version="3.6.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
Expand Down
2 changes: 1 addition & 1 deletion HubAndHost/Pages/Play.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
ViewData["Title"] = "Web version";
}

<component type="typeof(Snakes.Client.App)" render-mode="WebAssemblyPrerendered" />
<component type="typeof(Snakes.Client.App)" render-mode="WebAssembly" />
50 changes: 1 addition & 49 deletions HubAndHost/Pages/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorClient.styles.css" rel="stylesheet" />
<component type="typeof(HeadOutlet)" render-mode="WebAssemblyPrerendered" />
<component type="typeof(HeadOutlet)" render-mode="WebAssembly" />
</head>
<body>
@RenderBody()
Expand All @@ -32,53 +32,5 @@

<script src="_framework/blazor.webassembly.js"></script>
<script src="_content/Blazor.Extensions.Canvas/blazor.extensions.canvas.js"></script>

<script>
async function gameLoop(timeStamp) {
window.requestAnimationFrame(gameLoop);
await game.instance.invokeMethodAsync('GameLoop');
}

async function onKeyDown(e) {
await game.instance.invokeMethodAsync('OnKeyDown', e.keyCode);
}

async function onMouseDown(e) {
await game.instance.invokeMethodAsync('OnMouseDown', e.button);
}

function onMouseMove(e) {
game.instance.invokeMethod('OnMouseMove', e.clientX, e.clientY);
}

function onResize() {
if (!window.game.canvas)
return;

game.canvas.width = window.innerWidth;
game.canvas.height = window.innerHeight;

game.instance.invokeMethod('OnResize', window.innerWidth, window.innerHeight)
}

window.initGame = (instance) => {
var canvasContainer = document.getElementById('canvasContainer'),
canvases = canvasContainer.getElementsByTagName('canvas') || [];
window.game = {
instance: instance,
canvas: canvases.length ? canvases[0] : null
};

window.addEventListener("keydown", onKeyDown)
window.addEventListener("mousedown", onMouseDown);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("resize", onResize);

// Call once to set initial state.
onResize();

window.requestAnimationFrame(gameLoop);
};
</script>
</body>
</html>
26 changes: 26 additions & 0 deletions MauiBlazorClient/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Snakes.MauiBlazorClient"
x:Class="Snakes.MauiBlazorClient.App">
<Application.Resources>
<ResourceDictionary>

<Color x:Key="PageBackgroundColor">#512bdf</Color>
<Color x:Key="PrimaryTextColor">White</Color>

<Style TargetType="Label">
<Setter Property="TextColor" Value="{DynamicResource PrimaryTextColor}" />
<Setter Property="FontFamily" Value="OpenSansRegular" />
</Style>

<Style TargetType="Button">
<Setter Property="TextColor" Value="{DynamicResource PrimaryTextColor}" />
<Setter Property="FontFamily" Value="OpenSansRegular" />
<Setter Property="BackgroundColor" Value="#2b0b98" />
<Setter Property="Padding" Value="14,10" />
</Style>

</ResourceDictionary>
</Application.Resources>
</Application>
11 changes: 11 additions & 0 deletions MauiBlazorClient/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Snakes.MauiBlazorClient;

public partial class App : Application
{
public App()
{
InitializeComponent();

MainPage = new MainPage();
}
}
11 changes: 11 additions & 0 deletions MauiBlazorClient/Main.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Router AppAssembly="@typeof(Main).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
Loading