Skip to content

Commit

Permalink
Добавлен метод для установки цены финала
Browse files Browse the repository at this point in the history
  • Loading branch information
Fooxboy committed Jan 14, 2024
1 parent d3cbccc commit 09a013e
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 18 deletions.
11 changes: 2 additions & 9 deletions MyOwnGame.Backend/BackgroundTasks/BackgroundTaskRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,11 @@

namespace MyOwnGame.Backend.BackgroundTasks;

public class BackgroundTaskRunner
public class BackgroundTaskRunner(IEnumerable<IBackgroundTask> backgroundTasks)
{
private readonly IEnumerable<IBackgroundTask> _backgroundTasks;

public BackgroundTaskRunner(IEnumerable<IBackgroundTask> backgroundTasks)
{
_backgroundTasks = backgroundTasks;
}

public void Run()
{
foreach (var backgroundTask in _backgroundTasks)
foreach (var backgroundTask in backgroundTasks)
{
var thread = new Thread(async () =>
{
Expand Down
26 changes: 24 additions & 2 deletions MyOwnGame.Backend/Domain/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ public class Session
public string PackageHash { get; private set; }

public List<FinalAnswer> FinalAnswers { get; private set; }

public List<FinalPrice> FinalPrices { get; private set; }


public SessionSettings Settings { get; private set; }

Expand All @@ -69,6 +72,7 @@ public Session(Package package, SessionSettings? settings = null)
};

FinalAnswers = new List<FinalAnswer>();
FinalPrices = new List<FinalPrice>();

Settings = settings ?? new SessionSettings() { TimeToReadyAnswer = 5 };
}
Expand Down Expand Up @@ -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});
}
}
7 changes: 6 additions & 1 deletion MyOwnGame.Backend/Helpers/SessionEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,10 @@ public enum SessionEvents
/// <summary>
/// Сессия была завершена.
/// </summary>
SessionClosed
SessionClosed,

/// <summary>
/// Необходимо установить цену для игры в финале
/// </summary>
NeedSetFinalPrice,
}
17 changes: 16 additions & 1 deletion MyOwnGame.Backend/Hubs/SessionHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions MyOwnGame.Backend/Models/FinalPrice.cs
Original file line number Diff line number Diff line change
@@ -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; }
}
2 changes: 1 addition & 1 deletion MyOwnGame.Backend/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public static void Main(string[] args)
app.UseCors("any");

var backgroundTaskRunner = app.Services.GetRequiredService<BackgroundTaskRunner>();

backgroundTaskRunner.Run();

#if DEBUG
Expand Down
5 changes: 5 additions & 0 deletions MyOwnGame.Backend/Services/SessionCallbackService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
33 changes: 31 additions & 2 deletions MyOwnGame.Backend/Services/SessionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);

Expand Down
Binary file modified MyOwnGame.Backend/database.db
Binary file not shown.
28 changes: 26 additions & 2 deletions MyOwnGame.Backend/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,27 @@

> [!info] Примечание
Этот метод может вызывать только админ. Всем игрокам приходит событие `ChangeSelectQuestionPlayer`



----
### `SetFinalPrice`
Указать цену игры в финале
#### Аргументы:
1`int score` - *Количество очков поставленных на игру*

#### Результат: `null`

> [!info] Примечание
Невозможно указать меньше 1 или больше чем очков у игрока

----

----
### `SendFinalAnswer`
Отправить ответ на финал
#### Аргументы:
1. `string text` - *Ответ на вопрос*
2. `int score` - *количество отвеченных очков*
2. `int score` - *НИЧЕГО НЕ ДЕЛАЕТ, ОСТАВЛЕНО ДЛЯ ОБРАТНОЙ СОВМЕСТИМОСТИ*

#### Результат: `null`

Expand Down Expand Up @@ -443,6 +457,15 @@

1. `PlayerDto` - игрок, котому передали вопрос

----

### `NeedSetFinalPrice`
Необходимо выбрать цену игры в финале

#### Аргументы:

ничего

----
### `SessionClosed`
Эта сессия завершилась. Надо отключиться от хаба
Expand Down Expand Up @@ -581,6 +604,7 @@
3. `FreeQuestion` = 3 - вопрос без риска,
4. `Auction` = 4 - аукцион,
5. `Other` = 5 - другой (я не знаю что это из 1000 паков, ни разу не появлялся, но документации такое есть)
6. `Final` = 6 - Финальный вопрос

----

Expand Down

0 comments on commit 09a013e

Please sign in to comment.