Skip to content

Commit

Permalink
solving #17
Browse files Browse the repository at this point in the history
  • Loading branch information
macel94 committed Jan 17, 2024
1 parent 5784127 commit ddbc138
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 49 deletions.
104 changes: 58 additions & 46 deletions src/BlazorPong.Web.Components/PongComponent.razor
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,18 @@
}
else
{
<div>
<input type="text" @bind="tempRoomId" placeholder="Enter Room ID" />
<FluentButton @onclick="JoinRoom">Join Room</FluentButton>
</div>
<FluentButton @onclick="GenerateRoomId">Generate Room ID</FluentButton>
if (isLoadingRoomState)
{
<FluentProgressRing />
}
else
{
<div>
<input type="text" @bind="tempRoomId" placeholder="Enter Room ID" />
<FluentButton @onclick="() => ExecuteWithLoadingStateAsync(JoinRoomAsync)">Join Room</FluentButton>
</div>
<FluentButton @onclick="() => ExecuteWithLoadingStateAsync(OpenRoomAsync)">Create new Room</FluentButton>
}
}
</FluentStack>
}
Expand All @@ -64,16 +71,13 @@
<FluentGridItem xs="3">
<h4>Rendering DateTime Stack</h4>

@if (dateTimeArray.Any())
@if (dateTimeArray.Length > 0)
{
<ul>
@for (int i = 0; i < dateTimeArray.Length; i++)
{
var index = (currentIndex + i) % dateTimeArray.Length;
if (dateTimeArray[index] != default)
{
<li @key="index">@dateTimeArray[index].ToString("yyyy-MM-dd HH:mm:ss.fff")</li>
}
var tempValue = dateTimeArray[i];
<li @key="i">@(tempValue.HasValue ? tempValue.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") : "undefined")</li>
}
</ul>
}
Expand All @@ -85,15 +89,15 @@
<div id="gamearea">
@if (GameObjectsInitialized)
{
<div id="@(GameConstants.BallRoleAsString.ToLower())" style="@(Ball.ToStyle())" />
<div id="@(GameConstants.Player1RoleAsString.ToLower())" draggable=@(Player1.Draggable)
@ondragstart="@(e => SetInitialMouseOffset(e, Player1))"
@ondrag="@(e => MoveOnYAxisAndFlag(e, Player1))"
style="@Player1.ToStyle()" />
<div id="@(GameConstants.Player2RoleAsString.ToLower())" draggable=@(Player2.Draggable)
@ondragstart="@(e => SetInitialMouseOffset(e, Player2))"
@ondrag="@(e => MoveOnYAxisAndFlag(e, Player2))"
style="@Player2.ToStyle()" />
<div id="@(GameConstants.BallRoleAsString.ToLower())" style="@(Ball!.ToStyle())" />
<div id="@(GameConstants.Player1RoleAsString.ToLower())" draggable="true"
@ondragstart="@(e => SetInitialMouseOffset(e, Player1!))"
@ondrag="@(e => MoveOnYAxisAndFlag(e, Player1!))"
style="@Player1!.ToStyle()" />
<div id="@(GameConstants.Player2RoleAsString.ToLower())" draggable="true"
@ondragstart="@(e => SetInitialMouseOffset(e, Player2!))"
@ondrag="@(e => MoveOnYAxisAndFlag(e, Player2!))"
style="@Player2!.ToStyle()" />
}
</div>

Expand Down Expand Up @@ -155,15 +159,13 @@
private HttpTransportType connectionTypeChoice = HttpTransportType.WebSockets;
public IJSObjectReference? module { get; set; }
private double _containerHeight = 0;
// I Initialize this just because if not pre-populated it makes everything slide down on each of the first 5 updates and it feels like a 90'app
private DateTimeOffset[] dateTimeArray = new DateTimeOffset[3];
private DateTimeOffset?[] dateTimeArray = new DateTimeOffset?[3];
private int currentIndex = 0;
private bool NoConnectionOrInvalid => Connection == null || (Connection.State != HubConnectionState.Connected && Connection.State != HubConnectionState.Reconnecting);
private bool isLoadingRoomState = false;

public void SetInitialMouseOffset(DragEventArgs e, GameObject go)
{
Logger.LogInformation("Drag started for: " + go.Id);

// Assuming go.Top is the current top position of the element in percentage
var currentTopInPixels = (go.Top / 100) * _containerHeight;
_mouseOffset = e.ClientY - _containerTopOffset - currentTopInPixels;
Expand All @@ -180,12 +182,13 @@
"import", $"./_content/{assemblyName}/{nameof(PongComponent)}.razor.js");
_containerHeight = await module.InvokeAsync<double>("getContainerHeight");
_containerTopOffset = await module.InvokeAsync<double>("getContainerTopOffset", "gamearea");

if (RoomId.HasValue)
{
tempRoomId = RoomId.Value.ToString();
await ConnectToHub();
await JoinRoom();
StateHasChanged();
await JoinRoomAsync();
await InvokeAsync(StateHasChanged);
}
}
dateTimeArray[currentIndex] = SystemClock.UtcNow;
Expand Down Expand Up @@ -222,11 +225,11 @@
Connection.On<Roles, int>(nameof(IBlazorPongClient.UpdatePlayerPoints), UpdatePlayerPoints);
Connection.On<string>(nameof(IBlazorPongClient.UpdateGameMessage), UpdateGameMessage);

Logger.LogInformation("State: " + Connection.State.ToString() + "Type:" + connectionTypeChoice.ToString());
Logger.LogInformation("State: " + Connection.State.ToString() + "Type: " + connectionTypeChoice.ToString());

await Connection.StartAsync();

Logger.LogInformation("State: " + Connection.State.ToString() + "Type:" + connectionTypeChoice.ToString());
Logger.LogInformation("State: " + Connection.State.ToString() + "Type: " + connectionTypeChoice.ToString());

Logger.LogInformation("ConnectionId: " + Connection.ConnectionId?.ToString());
}
Expand Down Expand Up @@ -273,7 +276,7 @@

public void MoveOnYAxisAndFlag(DragEventArgs e, GameObject go)
{
if (!go.Draggable || e.ClientY <= 0)
if (!go.Id.Equals(_playerType!.Value.ToString()) || e.ClientY <= 0)
{
return;
}
Expand Down Expand Up @@ -306,6 +309,25 @@
StateHasChanged();
}

private async Task ExecuteWithLoadingStateAsync(Func<Task> action)
{
try
{
isLoadingRoomState = true;
await InvokeAsync(StateHasChanged);
await action();
}
catch (Exception ex)
{
Logger.LogInformation(ex.ToString());
}
finally
{
isLoadingRoomState = false;
await InvokeAsync(StateHasChanged);
}
}

// TODO - https://github.com/microsoft/dotnet-podcasts/blob/main/src/Web/Components/ListenTogetherHubClient.cs#L5
private async void UpdateServer(object? state)
{
Expand Down Expand Up @@ -344,19 +366,17 @@
{
// Chiedo al server la posizione di ogni oggetto e aspetto la risposta
GameObjectsDict = await Connection!.InvokeAsync<Dictionary<string, GameObject?>>(nameof(IGameHub.GetGameObjects), RoomId);

// Infine setto i draggable che non dipendono dal server
foreach (var kvpair in GameObjectsDict)
{
kvpair.Value!.Draggable = kvpair.Key.Equals(_playerType.ToString());
}
Logger.LogInformation("GameObjects initialization completed.");
}

public Task UpdateGameObjectPositionOnClient(GameObject? updatedObj)
{
if (GameMessage != null && GameMessage != "Game started!")
{
GameMessage = "Game started!";
_updateServerTimer = new Timer(UpdateServer, null, 1000, 10);

Logger.LogInformation("Timer Started!");
}

if (GameObjectsDict.TryGetValue(updatedObj!.Id, out var foundObj))
Expand Down Expand Up @@ -416,7 +436,7 @@
await InvokeAsync(StateHasChanged);
}

private async Task GenerateRoomId()
private async Task OpenRoomAsync()
{
RoomId = Guid.NewGuid();
NavigationManager.NavigateTo($"/room/{RoomId}/pong");
Expand All @@ -432,7 +452,7 @@
}
}

private async Task JoinRoom()
private async Task JoinRoomAsync()
{
if (Guid.TryParse(tempRoomId, out var roomId))
{
Expand All @@ -451,18 +471,10 @@

private async Task ManageEnteredPlayerTypeAssigned()
{
Logger.LogInformation("Player type:" + _playerType.ToString());
Logger.LogInformation($"Player type: {_playerType}");

PlayerTypeMessage = $"Your role is: {_playerType.ToString()}";

await GetOrInitializeGameObjects();

Logger.LogInformation("GameObjects initialization completed.");

// Ogni decimo di secondo controlliamo se necessario fare l'update delle collisioni al server e in caso lo mandiamo
// Iniziamo un secondo dopo l'inizializzazione del timer
_updateServerTimer = new Timer(UpdateServer, null, 1000, 10);

Logger.LogInformation("Timer Started!");
}
}
4 changes: 2 additions & 2 deletions src/BlazorPong.Web/Server/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Using .NET Chiseled image as the base
# Using .NET image as the base
FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy AS base
USER app
WORKDIR /app
Expand All @@ -22,7 +22,7 @@ FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./BlazorPong.Web.Server.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# Final stage, using the Chiseled base image
# Final stage, using the base image
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
Expand Down
1 change: 0 additions & 1 deletion src/BlazorPong.Web/Shared/GameObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ public record GameObject(string Id, double Width, double Height)
{
public double Left { get; set; }
public double Top { get; set; }
public bool Draggable { get; set; }
public long LastTickClientKnowsServerReceivedUpdate { get; set; }
public long LastTimeServerReceivedUpdate { get; set; }
public string? LastSinglaRServerReceivedUpdateName { get; set; }
Expand Down

0 comments on commit ddbc138

Please sign in to comment.