Moved some logic to other methods

This commit is contained in:
Martin Berg Alstad 2023-05-20 10:15:17 +02:00
parent d8e74dc6fd
commit 6f309a9b4a
3 changed files with 19 additions and 10 deletions

View File

@ -1,6 +1,4 @@
using System.Net.WebSockets;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using pacMan.Game;
using pacMan.Game.Interfaces;
@ -27,22 +25,26 @@ public class GameController : GenericController
protected override ArraySegment<byte> Run(WebSocketReceiveResult result, byte[] data)
{
var stringResult = data.GetString(data.Length);
// Removes invalid characters from the string
stringResult = Regex.Replace(stringResult, @"\p{C}+", "");
Logger.Log(LogLevel.Information, "Received: {}", stringResult);
var action = JsonSerializer.Deserialize<ActionMessage>(stringResult);
var action = ActionMessage.FromJson(stringResult);
switch (action?.Action)
DoAction(action);
return action.ToArraySegment();
}
private void DoAction(ActionMessage message)
{
switch (message.Action)
{
case GameAction.RollDice:
var rolls = _diceCup.Roll();
Logger.Log(LogLevel.Information, "Rolled {}", string.Join(", ", rolls));
action.Data = rolls;
return action.ToArraySegment();
message.Data = rolls;
break;
default:
return new ArraySegment<byte>("Invalid action"u8.ToArray());
throw new ArgumentOutOfRangeException(nameof(message), "Action not allowed");
}
}
}

View File

@ -1,3 +1,5 @@
using System.Text.Json;
namespace pacMan.Game;
public enum GameAction
@ -9,6 +11,8 @@ public class ActionMessage<T>
{
public GameAction Action { get; set; }
public T? Data { get; set; }
public static ActionMessage FromJson(string json) => JsonSerializer.Deserialize<ActionMessage>(json)!;
}
public class ActionMessage : ActionMessage<dynamic>

View File

@ -1,5 +1,6 @@
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace pacMan.Utils;
@ -7,7 +8,9 @@ public static class Extensions
{
public static string GetString(this byte[] bytes, int length)
{
return Encoding.UTF8.GetString(bytes, 0, length);
var s = Encoding.UTF8.GetString(bytes, 0, length);
// Removes invalid characters from the string
return Regex.Replace(s, @"\p{C}+", "");
}
public static ArraySegment<byte> ToArraySegment(this object obj)