66 lines
2.3 KiB
C#
66 lines
2.3 KiB
C#
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
|
using Gameboard.ShogiUI.Sockets.Models;
|
|
using Gameboard.ShogiUI.Sockets.Repositories;
|
|
using Newtonsoft.Json;
|
|
using System.Threading.Tasks;
|
|
using Service = Gameboard.ShogiUI.Sockets.ServiceModels.Socket;
|
|
|
|
|
|
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
|
{
|
|
public class MoveHandler : IActionHandler
|
|
{
|
|
private readonly IBoardManager boardManager;
|
|
private readonly IGameboardRepository gameboardRepository;
|
|
private readonly ISocketCommunicationManager communicationManager;
|
|
public MoveHandler(
|
|
IBoardManager boardManager,
|
|
ISocketCommunicationManager communicationManager,
|
|
IGameboardRepository gameboardRepository)
|
|
{
|
|
this.boardManager = boardManager;
|
|
this.gameboardRepository = gameboardRepository;
|
|
this.communicationManager = communicationManager;
|
|
}
|
|
|
|
public async Task Handle(string json, string userName)
|
|
{
|
|
var request = JsonConvert.DeserializeObject<Service.Messages.MoveRequest>(json);
|
|
var moveModel = new Move(request.Move);
|
|
var board = boardManager.Get(request.GameName);
|
|
if (board == null)
|
|
{
|
|
// TODO: Find a flow for this
|
|
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
|
{
|
|
Error = $"Game isn't loaded. Send a message with the {Service.Types.ClientAction.LoadGame} action first."
|
|
};
|
|
await communicationManager.BroadcastToPlayers(response, userName);
|
|
|
|
}
|
|
var boardMove = moveModel.ToBoardModel();
|
|
var moveSuccess = board.Move(boardMove);
|
|
if (moveSuccess)
|
|
{
|
|
await gameboardRepository.PostMove(request.GameName, new PostMove(moveModel.ToApiModel()));
|
|
var boardState = new BoardState(board);
|
|
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
|
{
|
|
GameName = request.GameName,
|
|
PlayerName = userName,
|
|
BoardState = boardState.ToServiceModel()
|
|
};
|
|
await communicationManager.BroadcastToGame(request.GameName, response);
|
|
}
|
|
else
|
|
{
|
|
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
|
{
|
|
Error = "Invalid move."
|
|
};
|
|
await communicationManager.BroadcastToPlayers(response, userName);
|
|
}
|
|
}
|
|
}
|
|
}
|