using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using…
- User
using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Menu; using CounterStrikeSharp.API.Modules.Utils; using CustomRounds.Rounds; using Microsoft.Extensions.DependencyInjection;
namespace CustomRounds;
public class CustomRoundsManager { private readonly IServiceProvider _serviceProvider; private readonly Plugin _plugin; private readonly CustomRoundsTypes _roundTypes; private readonly Config _config; private readonly Queue<(string Name, Type Round)> _currentRounds = new(); private ICustomRound? _currentRound;
public CustomRoundsManager(IServiceProvider serviceProvider, Plugin plugin, CustomRoundsTypes roundTypes, Config<MainConfig> config) { _serviceProvider = serviceProvider; _plugin = plugin; _roundTypes = roundTypes; _config = config; plugin.RegisterListener<Listeners.OnMapStart>(OnMapStart); plugin.RegisterEventHandler<EventRoundStart>(EventRoundStart); plugin.RegisterEventHandler<EventRoundEnd>(EventRoundEnd); plugin.AddCommand("css_cr", "", OnCustomRoundsCommand); } private void OnCustomRoundsCommand(CCSPlayerController? player, CommandInfo commandinfo) { var menu = new CenterHtmlMenu("Custom Rounds", _plugin); foreach (var round in _roundTypes) { menu.AddMenuOption(round.Key, (controller, option) => { Server.ExecuteCommand("mp_warmup_end"); _plugin.AddTimer(2.0f, () => StartRound(round.Value)); }); } } private HookResult EventRoundStart(EventRoundStart @event, GameEventInfo info) { if (!_currentRounds.TryDequeue(out var roundType)) return HookResult.Continue; var gameRules = Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").First().GameRules; if (gameRules is null || gameRules.WarmupPeriod) return HookResult.Continue; StartRound(roundType.Round); return HookResult.Continue; } private void StartRound(Type type) { if (_currentRound != null) { _currentRound.End(); _currentRound = null; } var round = (ICustomRound)_serviceProvider.GetRequiredService(type); Server.NextFrame(() => round.Start()); _currentRound = round; } private HookResult EventRoundEnd(EventRoundEnd @event, GameEventInfo info) { if (_currentRound is not null) { _currentRound.End(); _currentRound = null; } return HookResult.Continue; } private void OnMapStart(string map) { var roundNames = _config.Value.Rounds.OrderBy(x => Guid.NewGuid()); foreach (var (key, value) in roundNames) { var type = _roundTypes[key]; for (var i = 0; i < value; i++) { _currentRounds.Enqueue((key, type)); } } }}
public class CustomRoundsTypes : Dictionary<string, Type> { public void Scan(IServiceCollection collection) { foreach (var serviceType in typeof(Plugin).Assembly.GetTypes() .Where(t => t != typeof(ICustomRound) && t.IsAssignableTo(typeof(ICustomRound)))) { var attribute = serviceType.GetCustomAttribute(); if (attribute is null) continue;
- Assistant
- User
- Assistant
- User
- Assistant
- User
может потмоу что в EventRoundEnd мы не делаем этого?
_currentRound = (ICustomRound)_serviceProvider.GetRequiredService(nextRound.Round);
- Assistant
Да, вы правы. В текущем коде, похоже, мы не начинаем следующий раунд после завершения текущего. Давайте добавим логику, чтобы запустить следующий раунд из очереди в методе
EventRoundEnd.Вы можете обновить
EventRoundEnd, чтобы он автоматически запускал следующий раунд, если в очереди ещё остались раунды. Это решит проблему с тем, что раунды не начинаются повторно.Вот как это можно сделать:
private HookResult EventRoundEnd(EventRoundEnd @event, GameEventInfo info) { if (_currentRound != null) { Console.WriteLine($"CALLED END"); _currentRound.End(); _currentRound = null; } if (_currentRounds.Count > 0) { var nextRound = _currentRounds.Peek(); var roundName = nextRound.Name; if (_roundCounts.TryGetValue(roundName, out var count)) { if (count > 1) { _roundCounts[roundName] = count - 1; } else { _currentRounds.Dequeue(); } // Запуск следующего раунда _currentRound = (ICustomRound)_serviceProvider.GetRequiredService(nextRound.Round); Server.NextFrame(() => _currentRound.Start()); } } return HookResult.Continue; } - User
- Assistant
- User
- Assistant
- User
т.е если я оставлю
if (!_currentRounds.TryDequeue(out var roundType)) return HookResult.Continue;вот это, то раунд все равно вызовится?
- Assistant
Ваш вопрос касается того, как метод
EventRoundStartбудет функционировать, если оставить строку сTryDequeue. Давайте разберёмся, как это работает.Как работает
TryDequeue:Метод
TryDequeueизQueueпытается извлечь элемент из очереди. Он возвращаетtrueи устанавливаетroundTypeзначением первого элемента очереди, если тот существует; иначе, возвращаетfalseи сохраняетroundTypeкак значение по умолчанию. - User
мне нужно сделать так, чтобы если человек в меню выбрал другой раунд, то он перезапустился уже с новым раундом
- Assistant
- User
нет, мне нужно написать mp_restartgame 1
- Assistant