From 09a013ef725b80ed3607f5ad53019dfb9d70a1d4 Mon Sep 17 00:00:00 2001 From: Fooxboy Date: Sun, 14 Jan 2024 20:16:49 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B8=20=D1=86?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D1=84=D0=B8=D0=BD=D0=B0=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BackgroundTasks/BackgroundTaskRunner.cs | 11 ++---- MyOwnGame.Backend/Domain/Session.cs | 26 ++++++++++++-- MyOwnGame.Backend/Helpers/SessionEvents.cs | 7 +++- MyOwnGame.Backend/Hubs/SessionHub.cs | 17 ++++++++- MyOwnGame.Backend/Models/FinalPrice.cs | 10 ++++++ MyOwnGame.Backend/Program.cs | 2 +- .../Services/SessionCallbackService.cs | 5 +++ MyOwnGame.Backend/Services/SessionService.cs | 33 ++++++++++++++++-- MyOwnGame.Backend/database.db | Bin 40960 -> 40960 bytes MyOwnGame.Backend/readme.md | 28 +++++++++++++-- 10 files changed, 121 insertions(+), 18 deletions(-) create mode 100644 MyOwnGame.Backend/Models/FinalPrice.cs diff --git a/MyOwnGame.Backend/BackgroundTasks/BackgroundTaskRunner.cs b/MyOwnGame.Backend/BackgroundTasks/BackgroundTaskRunner.cs index 7253098..c04e3c6 100644 --- a/MyOwnGame.Backend/BackgroundTasks/BackgroundTaskRunner.cs +++ b/MyOwnGame.Backend/BackgroundTasks/BackgroundTaskRunner.cs @@ -2,18 +2,11 @@ namespace MyOwnGame.Backend.BackgroundTasks; -public class BackgroundTaskRunner +public class BackgroundTaskRunner(IEnumerable backgroundTasks) { - private readonly IEnumerable _backgroundTasks; - - public BackgroundTaskRunner(IEnumerable backgroundTasks) - { - _backgroundTasks = backgroundTasks; - } - public void Run() { - foreach (var backgroundTask in _backgroundTasks) + foreach (var backgroundTask in backgroundTasks) { var thread = new Thread(async () => { diff --git a/MyOwnGame.Backend/Domain/Session.cs b/MyOwnGame.Backend/Domain/Session.cs index 6515caf..73d37e5 100644 --- a/MyOwnGame.Backend/Domain/Session.cs +++ b/MyOwnGame.Backend/Domain/Session.cs @@ -45,6 +45,9 @@ public class Session public string PackageHash { get; private set; } public List FinalAnswers { get; private set; } + + public List FinalPrices { get; private set; } + public SessionSettings Settings { get; private set; } @@ -69,6 +72,7 @@ public Session(Package package, SessionSettings? settings = null) }; FinalAnswers = new List(); + FinalPrices = new List(); Settings = settings ?? new SessionSettings() { TimeToReadyAnswer = 5 }; } @@ -220,8 +224,26 @@ public void RemoveTheme(int position) CurrentRound.Themes.Remove(CurrentRound.Themes[position]); } - public void AddFinalAnswer(Player player, string answer, int price) + public void AddFinalAnswer(Player player, string answer) { - FinalAnswers.Add(new FinalAnswer(){ Player = player, Answer = answer, Price = price}); + + var price = FinalPrices.FirstOrDefault(x => x.Player.Id == player.Id)?.Price; + + if (price is null) + { + throw new Exception("Пользователь не указал количество баллов на какое он играет в финале"); + } + + FinalAnswers.Add(new FinalAnswer(){ Player = player, Answer = answer, Price = price.Value}); + } + + public void AddFinalPrice(Player player, int price) + { + if (price < 1 || price > player.Score) + { + throw new Exception("Невозможно установить количество за пределами доступного"); + } + + FinalPrices.Add(new FinalPrice(){ Player = player, Price = price}); } } \ No newline at end of file diff --git a/MyOwnGame.Backend/Helpers/SessionEvents.cs b/MyOwnGame.Backend/Helpers/SessionEvents.cs index 8c7a4e2..33416dc 100644 --- a/MyOwnGame.Backend/Helpers/SessionEvents.cs +++ b/MyOwnGame.Backend/Helpers/SessionEvents.cs @@ -133,5 +133,10 @@ public enum SessionEvents /// /// Сессия была завершена. /// - SessionClosed + SessionClosed, + + /// + /// Необходимо установить цену для игры в финале + /// + NeedSetFinalPrice, } \ No newline at end of file diff --git a/MyOwnGame.Backend/Hubs/SessionHub.cs b/MyOwnGame.Backend/Hubs/SessionHub.cs index 297527e..4132f68 100644 --- a/MyOwnGame.Backend/Hubs/SessionHub.cs +++ b/MyOwnGame.Backend/Hubs/SessionHub.cs @@ -260,13 +260,28 @@ public async Task ChangeSelectQuestionPlayer(int playerId) } } + public async Task SetFinalPrice(int price) + { + try + { + _logger.LogInformation($"Установка цены для финала в размере: {price}"); + + await _sessionService.SendFinalPrice(price, Context.ConnectionId); + } + catch (Exception ex) + { + _logger.LogError(ex, ex.Message); + throw new HubException(ex.Message, ex); + } + } + public async Task SendFinalAnswer(string text, int price) { try { _logger.LogInformation($"Отправка финального ответа от пользователя '{Context.ConnectionId}' '{text}'"); - await _sessionService.SendFinalAnswer(text, price, Context.ConnectionId); + await _sessionService.SendFinalAnswer(text, Context.ConnectionId); } catch (Exception ex) diff --git a/MyOwnGame.Backend/Models/FinalPrice.cs b/MyOwnGame.Backend/Models/FinalPrice.cs new file mode 100644 index 0000000..ff2e22a --- /dev/null +++ b/MyOwnGame.Backend/Models/FinalPrice.cs @@ -0,0 +1,10 @@ +using MyOwnGame.Backend.Domain; + +namespace MyOwnGame.Backend.Models; + +public class FinalPrice +{ + public Player Player { get; set; } + + public int Price { get; set; } +} \ No newline at end of file diff --git a/MyOwnGame.Backend/Program.cs b/MyOwnGame.Backend/Program.cs index a21ccfa..da7ce39 100644 --- a/MyOwnGame.Backend/Program.cs +++ b/MyOwnGame.Backend/Program.cs @@ -122,7 +122,7 @@ public static void Main(string[] args) app.UseCors("any"); var backgroundTaskRunner = app.Services.GetRequiredService(); - + backgroundTaskRunner.Run(); #if DEBUG diff --git a/MyOwnGame.Backend/Services/SessionCallbackService.cs b/MyOwnGame.Backend/Services/SessionCallbackService.cs index 8cfeb22..6c788ed 100644 --- a/MyOwnGame.Backend/Services/SessionCallbackService.cs +++ b/MyOwnGame.Backend/Services/SessionCallbackService.cs @@ -146,6 +146,11 @@ await _hubContext.Clients.Group(session.ToString()).SendAsync(SessionEvents.User PlayerDto.Create(finalAnswer.Player), finalAnswer); } + public async Task NeedSetFinalPrice(long sessionId) + { + await _hubContext.Clients.Group(sessionId.ToString()).SendAsync(SessionEvents.NeedSetFinalPrice.ToString()); + } + public async Task PlayerOffline(long sessionId, Player player) { await _hubContext.Clients.Group(sessionId.ToString()) diff --git a/MyOwnGame.Backend/Services/SessionService.cs b/MyOwnGame.Backend/Services/SessionService.cs index df159ff..2eab2cd 100644 --- a/MyOwnGame.Backend/Services/SessionService.cs +++ b/MyOwnGame.Backend/Services/SessionService.cs @@ -630,12 +630,41 @@ public async Task RemoveFinalTheme(int position, string connectionId) await _callbackService.ChangeSelectQuestionPlayer(player.SessionId, nextPlayer); if (session.CurrentRound.Themes.Count == 1) + { + await _callbackService.NeedSetFinalPrice(player.SessionId); + } + } + + public async Task SendFinalPrice(int price, string connectionId) + { + var session = _sessionsManager.GetSessionByConnection(connectionId); + + if (session is null) + { + throw new Exception("Не найдена сессия :("); + } + + var player = _sessionsManager.GetPlayer(connectionId); + + if (player is null) + { + throw new Exception("Не найден игрок, который отправил ответ"); + } + + if (session.FinalPrices.Any(x => x.Player.Id == player.Id)) + { + throw new Exception("Вы уже установили сумму на финал"); + } + + session.AddFinalPrice(player, price); + + if (session.Players.Count(x => x is { IsAdmin: false, IsDisconnected: false }) >= session.FinalPrices.Count) { await SelectFinalTheme(session, player); } } - public async Task SendFinalAnswer(string message, int price, string connectionId) + public async Task SendFinalAnswer(string message, string connectionId) { var session = _sessionsManager.GetSessionByConnection(connectionId); @@ -651,7 +680,7 @@ public async Task SendFinalAnswer(string message, int price, string connectionId throw new Exception("Не найден игрок, который отправил ответ"); } - session.AddFinalAnswer(player, message, price); + session.AddFinalAnswer(player, message); await _callbackService.FinalQuestionResponsed(player.SessionId, player); diff --git a/MyOwnGame.Backend/database.db b/MyOwnGame.Backend/database.db index 9c18d87ec516f4fc8fc98bd5fc3e4fc2cb8ccddf..20dbe2d1313592fe55e39062901b35cb536071a9 100644 GIT binary patch delta 348 zcmZoTz|?SnX@j@}N2a$h14FiO#%6hkI7Y^d&5e#0jGMPPMG7#cPZkK4Gh<|7U|=x( z4+2a;RvL)NU`_*)U;vgjf=j1^q#2phH(va~#Uan&BP`FLE4(=+ZnGkXaik~%L#3$E zX8DGGk$SL>WT0Z9_{slrmCFvR`rJ5QT7^fH~nWyR%_Fy)EfHEyYYPs{rWL Uy__7$3}T|03~NOu+sr=#0JjHXG5`Po delta 72 zcmV-O0Jr~uzyg540 [!info] Примечание Этот метод может вызывать только админ. Всем игрокам приходит событие `ChangeSelectQuestionPlayer` - + + +---- +### `SetFinalPrice` +Указать цену игры в финале +#### Аргументы: +1`int score` - *Количество очков поставленных на игру* + +#### Результат: `null` + +> [!info] Примечание +Невозможно указать меньше 1 или больше чем очков у игрока + +---- + ---- ### `SendFinalAnswer` Отправить ответ на финал #### Аргументы: 1. `string text` - *Ответ на вопрос* -2. `int score` - *количество отвеченных очков* +2. `int score` - *НИЧЕГО НЕ ДЕЛАЕТ, ОСТАВЛЕНО ДЛЯ ОБРАТНОЙ СОВМЕСТИМОСТИ* #### Результат: `null` @@ -443,6 +457,15 @@ 1. `PlayerDto` - игрок, котому передали вопрос +---- + +### `NeedSetFinalPrice` +Необходимо выбрать цену игры в финале + +#### Аргументы: + +ничего + ---- ### `SessionClosed` Эта сессия завершилась. Надо отключиться от хаба @@ -581,6 +604,7 @@ 3. `FreeQuestion` = 3 - вопрос без риска, 4. `Auction` = 4 - аукцион, 5. `Other` = 5 - другой (я не знаю что это из 1000 паков, ни разу не появлялся, но документации такое есть) +6. `Final` = 6 - Финальный вопрос ----