Skip to content

Commit

Permalink
#161 Replace inheritance with aggregation in logic classes
Browse files Browse the repository at this point in the history
  • Loading branch information
VladimirKhil committed Nov 18, 2023
1 parent cdb4468 commit 1ab633e
Show file tree
Hide file tree
Showing 14 changed files with 189 additions and 190 deletions.
2 changes: 1 addition & 1 deletion src/SICore/SICore/Clients/IPersonLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/// <summary>
/// Provides common behavior for player and showman.
/// </summary>
public interface IPersonLogic : IViewerLogic
public interface IPersonLogic
{
void OnInitialized();

Expand Down
44 changes: 20 additions & 24 deletions src/SICore/SICore/Clients/Player/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace SICore;
/// <summary>
/// Represents a game player.
/// </summary>
public sealed class Player : Viewer<IPlayerLogic>
public sealed class Player : Viewer
{
private readonly object _readyLock = new();

Expand Down Expand Up @@ -109,11 +109,6 @@ public Player(Client client, Account personData, bool isHost, ILocalizer localiz
ClientData.AutoReadyChanged += ClientData_AutoReadyChanged;
}

protected override IPlayerLogic CreateLogic(Account personData) =>
personData.IsHuman ?
new PlayerHumanLogic(ClientData, null, _viewerActions, LO) :
new PlayerComputerLogic(ClientData, (ComputerAccount)personData, _viewerActions);

public override ValueTask DisposeAsync(bool disposing)
{
ClientData.AutoReadyChanged -= ClientData_AutoReadyChanged;
Expand All @@ -131,6 +126,7 @@ private void ClientData_AutoReadyChanged()
}

var readyCommand = ((PersonAccount)ClientData.Me).BeReadyCommand;

if (ClientData.AutoReady && readyCommand != null)
{
readyCommand.Execute(null);
Expand All @@ -152,7 +148,7 @@ private async void ReleaseGameButton()
}
}

private void Clear() => _logic.Clear();
private void Clear() => _logic.PlayerLogic.Clear();

public override void Init()
{
Expand All @@ -166,7 +162,7 @@ public override void Init()
{
var readyCommand = personAccount.BeReadyCommand = new CustomCommand(arg => _viewerActions.SendMessage(Messages.Ready));
personAccount.BeUnReadyCommand = new CustomCommand(arg => _viewerActions.SendMessage(Messages.Ready, "-"));
_logic.OnInitialized();
_logic.PlayerLogic.OnInitialized();

if (ClientData.AutoReady)
{
Expand Down Expand Up @@ -232,12 +228,12 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams

if (mparams[1] == "1")
{
_logic.ChooseQuest();
_logic.PlayerLogic.ChooseQuest();
ClientData.Hint = LO[nameof(R.HintSelectQuestion)];
}
else
{
_logic.ChooseFinalTheme();
_logic.PlayerLogic.ChooseFinalTheme();
ClientData.Hint = LO[nameof(R.HintSelectTheme)];
}

Expand All @@ -259,7 +255,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
break;

case Messages.Atom: // deprecated
_logic.OnPlayerAtom(mparams);
_logic.PlayerLogic.OnPlayerAtom(mparams);

if (ClientData.QuestionType == QuestionTypes.Simple)
{
Expand All @@ -272,7 +268,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
break;

case Messages.Content:
_logic.OnPlayerAtom(mparams);
_logic.PlayerLogic.OnPlayerAtom(mparams);

if (ClientData.QuestionType == QuestionTypes.Simple)
{
Expand All @@ -293,7 +289,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
ClientData.PlayerDataExtensions.MyTry = true;
_buttonDisabledByGame = false;
EnableGameButton();
_logic.StartThink();
_logic.PlayerLogic.StartThink();
break;

case Messages.EndTry:
Expand All @@ -302,7 +298,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams

if (mparams[1] == MessageParams.EndTry_All)
{
_logic.EndThink();
_logic.PlayerLogic.EndThink();

ClientData.PlayerDataExtensions.Apellate.CanBeExecuted = ClientData.PlayerDataExtensions.ApellationCount > 0;
ClientData.PlayerDataExtensions.Pass.CanBeExecuted = false;
Expand All @@ -311,7 +307,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams

case Messages.Answer:
ClientData.PersonDataExtensions.Answer = "";
_logic.Answer();
_logic.PlayerLogic.Answer();
break;

case Messages.Cat:
Expand All @@ -324,7 +320,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams

ClientData.Hint = LO[nameof(R.HintSelectCatPlayer)];

_logic.Cat();
_logic.PlayerLogic.Cat();
break;

case Messages.CatCost:
Expand All @@ -336,7 +332,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
Stake = int.Parse(mparams[1])
};

_logic.CatCost();
_logic.PlayerLogic.CatCost();
break;

case Messages.Stake:
Expand All @@ -358,7 +354,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
Stake = int.Parse(mparams[5])
};

_logic.Stake();
_logic.PlayerLogic.Stake();
break;

case Messages.Stake2:
Expand Down Expand Up @@ -388,7 +384,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
Stake = minimumStake
};

_logic.Stake();
_logic.PlayerLogic.Stake();
break;

case Messages.FinalStake:
Expand All @@ -404,7 +400,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
ClientData.DialogMode = DialogModes.FinalStake;
((PlayerAccount)ClientData.Me).IsDeciding = false;

_logic.FinalStake();
_logic.PlayerLogic.FinalStake();
break;

case Messages.Validation:
Expand All @@ -430,7 +426,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
break;
}

_logic.PersonAnswered(playerIndex, isRight);
_logic.PlayerLogic.PersonAnswered(playerIndex, isRight);
break;

case Messages.Report:
Expand All @@ -450,7 +446,7 @@ protected override async ValueTask OnSystemMessageReceivedAsync(string[] mparams
ClientData.PlayerDataExtensions.Report.Report = report.ToString();
ClientData.DialogMode = DialogModes.Report;
((PlayerAccount)ClientData.Me).IsDeciding = false;
_logic.Report();
_logic.PlayerLogic.Report();
break;
}
}
Expand All @@ -464,7 +460,7 @@ private void OnValidation(string[] mparams)
{
ClientData.PersonDataExtensions.ValidatorName = mparams[1];
ClientData.PersonDataExtensions.Answer = mparams[2];
_logic.IsRight(mparams[3] == "+");
_logic.PlayerLogic.IsRight(mparams[3] == "+");
_ = int.TryParse(mparams[4], out var rightAnswersCount);
rightAnswersCount = Math.Min(rightAnswersCount, mparams.Length - 5);

Expand Down Expand Up @@ -494,7 +490,7 @@ private void OnValidation2(string[] mparams)
{
ClientData.PersonDataExtensions.ValidatorName = mparams[1];
ClientData.PersonDataExtensions.Answer = mparams[2];
_logic.IsRight(mparams[3] == "+");
_logic.PlayerLogic.IsRight(mparams[3] == "+");
_ = int.TryParse(mparams[5], out var rightAnswersCount);
rightAnswersCount = Math.Min(rightAnswersCount, mparams.Length - 6);

Expand Down
51 changes: 38 additions & 13 deletions src/SICore/SICore/Clients/Player/PlayerComputerLogic.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using SICore.Clients.Player;
using SICore.Extensions;
using SICore.Models;
using SICore.Utils;
using SIData;
using SIPackages.Core;
Expand All @@ -11,30 +12,42 @@ namespace SICore;
/// <summary>
/// Логика игрока-компьютера
/// </summary>
internal sealed class PlayerComputerLogic : ViewerComputerLogic, IPlayerLogic
internal sealed class PlayerComputerLogic : IPlayerLogic
{
private ComputerAccount _account;
//private readonly ViewerActions _viewerActions;
//private readonly ViewerData _data;
private readonly ViewerActions _viewerActions;
private readonly ViewerData _data;

private readonly TimerInfo[] _timersInfo;

/// <summary>
/// Создание логики
/// </summary>
/// <param name="client">Текущий клиент</param>
public PlayerComputerLogic(ViewerData data, ComputerAccount account, ViewerActions viewerActions)
: base(data, viewerActions, account)
public PlayerComputerLogic(ViewerData data, ComputerAccount account, ViewerActions viewerActions, TimerInfo[] timerInfos)
{
_account = account;
//_viewerActions = viewerActions;
//_data = data;
_viewerActions = viewerActions;
_data = data;
_timersInfo = timerInfos;
}

internal void ScheduleExecution(PlayerTasks task, double taskTime) => ScheduleExecution((int)task, 0, taskTime);

protected override void ExecuteTask(int taskId, int arg)
private async void ScheduleExecution(PlayerTasks task, double taskTime)
{
var task = (PlayerTasks)taskId;
await Task.Delay((int)taskTime * 100);

try
{
ExecuteTask(task);
}
catch (Exception exc)
{
_data.SystemLog.AppendFormat("Execution error: {0}", exc.ToString()).AppendLine();
}
}

private void ExecuteTask(PlayerTasks task)
{
switch (task)
{
case PlayerTasks.Ready:
Expand Down Expand Up @@ -86,6 +99,19 @@ protected override void ExecuteTask(int taskId, int arg)
}
}

private int GetTimePercentage(int timerIndex)
{
var now = DateTime.UtcNow;
var timer = _timersInfo[timerIndex];

if (!timer.IsEnabled)
{
return timer.PauseTime > -1 ? 100 * timer.PauseTime / timer.MaxTime : 0;
}

return (int)(100 * (now - timer.StartTime).TotalMilliseconds / (timer.EndTime - timer.StartTime).TotalMilliseconds);
}

private void PressButton() => _viewerActions.PressGameButton();

private void AnswerRight() => _viewerActions.SendMessage(Messages.IsRight, "+");
Expand Down Expand Up @@ -911,9 +937,8 @@ internal static StakeMode MakeStake(
}

/// <summary>
/// Является ли ситуация критической
/// Checks if situation is critical.
/// </summary>
/// <returns></returns>
private bool IsCritical()
{
int numQu;
Expand Down
33 changes: 15 additions & 18 deletions src/SICore/SICore/Clients/Player/PlayerHumanLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ namespace SICore;
/// <summary>
/// Логика игрока-человека
/// </summary>
internal sealed class PlayerHumanLogic : ViewerHumanLogic, IPlayerLogic
internal sealed class PlayerHumanLogic : IPlayerLogic, IDisposable
{
//private readonly ViewerActions _viewerActions;
//private readonly ViewerData _data;
//private readonly ILocalizer _localizer;
private readonly ViewerActions _viewerActions;
private readonly ViewerData _data;
private readonly ILocalizer _localizer;

//public TableInfoViewModel TInfo { get; }
public TableInfoViewModel TInfo { get; }

private readonly CancellationTokenSource _cancellationTokenSource = new();

Expand All @@ -25,12 +25,11 @@ public PlayerHumanLogic(
TableInfoViewModel tableInfoViewModel,
ViewerActions viewerActions,
ILocalizer localizer)
: base(data, viewerActions, localizer)
{
//_viewerActions = viewerActions;
//_data = data;
//_localizer = localizer;
//TInfo = tableInfoViewModel;
_viewerActions = viewerActions;
_data = data;
_localizer = localizer;
TInfo = tableInfoViewModel;

TInfo.QuestionSelected += PlayerClient_QuestionSelected;
TInfo.ThemeSelected += PlayerClient_ThemeSelected;
Expand All @@ -40,7 +39,7 @@ public PlayerHumanLogic(
TInfo.SelectTheme.CanBeExecuted = false;
}

private void TInfo_AnswerSelected(ItemViewModel item) => ClientData.PlayerDataExtensions.SendAnswer.Execute(item.Label);
private void TInfo_AnswerSelected(ItemViewModel item) => _data.PlayerDataExtensions.SendAnswer.Execute(item.Label);

#region PlayerInterface Members

Expand Down Expand Up @@ -75,8 +74,8 @@ public void Answer()

if (TInfo.LayoutMode == LayoutMode.Simple)
{
ClientData.DialogMode = DialogModes.Answer;
((PlayerAccount)ClientData.Me).IsDeciding = false;
_data.DialogMode = DialogModes.Answer;
((PlayerAccount)_data.Me).IsDeciding = false;

StartSendingVersion(_cancellationTokenSource.Token);
}
Expand Down Expand Up @@ -165,8 +164,8 @@ private async void Greet()
{
await Task.Delay(2000);

AddLog(string.Format(_viewerActions.LO[nameof(R.Hint)], _data.Host.GameButtonKey));
AddLog(_viewerActions.LO[nameof(R.PressButton)] + Environment.NewLine);
_data.OnAddString(null, string.Format(_viewerActions.LO[nameof(R.Hint)], _data.Host.GameButtonKey), LogMode.Log);
_data.OnAddString(null, _viewerActions.LO[nameof(R.PressButton)] + Environment.NewLine, LogMode.Log);
}
catch (ObjectDisposedException)
{
Expand Down Expand Up @@ -245,11 +244,9 @@ public void OnPlayerAtom(string[] mparams)

}

protected override ValueTask DisposeAsync(bool disposing)
public void Dispose()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();

return base.DisposeAsync(disposing);
}
}
Loading

0 comments on commit 1ab633e

Please sign in to comment.