Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spacelaw Change Rule #97

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Content.Server._CorvaxNext.StationEvents.Events;
using Content.Shared.Dataset;
using Robust.Shared.Prototypes;

namespace Content.Server._CorvaxNext.StationEvents.Components
{
[RegisterComponent, Access(typeof(SpaceLawChangeRule))]
public sealed partial class SpaceLawChangeRuleComponent : Component
{
/// <summary>
/// Localization key of a random message selected for the current event
/// </summary>
/// <remarks>
/// Do not set an initial value for this field!
/// </remarks>
[DataField]
public string? RandomMessage { get; set; }

/// <summary>
/// A localized dataset containing the initial list of all laws for the event
/// </summary>
[DataField]
public ProtoId<LocalizedDatasetPrototype> LawLocalizedDataset { get; set; }

/// <summary>
/// Time before changes to the law come into force.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Time before changes to the law come into force.
/// Time in minutes before changes to the law come into force.

/// Necessary for establish the delay in sending information about the law coming into force
/// </summary>
[DataField]
public int AdaptationTime { get; set; } = 10;
}
}
149 changes: 149 additions & 0 deletions Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
using System.Linq;
using Content.Server.Chat.Systems;
using Content.Server.Fax;
using Content.Shared.GameTicking.Components;
using Content.Server.GameTicking;
using Content.Shared._CorvaxNext.NextVars;
using Content.Shared.Paper;
using Content.Shared.Dataset;
using Robust.Shared.Random;
using Content.Shared.Fax.Components;
using Content.Server.StationEvents.Events;
using Robust.Shared.Timing;
using Robust.Shared.Prototypes;
using Robust.Shared.Configuration;
using Content.Server._CorvaxNext.StationEvents.Components;

namespace Content.Server._CorvaxNext.StationEvents.Events
{
public sealed class SpaceLawChangeRule : StationEventSystem<SpaceLawChangeRuleComponent>
{
[Dependency] private readonly ChatSystem _chat = default!;
[Dependency] private readonly IRobustRandom _robustRandom = default!;
[Dependency] private readonly FaxSystem _faxSystem = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly GameTicker _gameTicker = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;

/// <summary>
/// Sequence of laws to be used for the current event
/// </summary>
private List<string> _sequenceLaws = new();

protected override void Started(EntityUid uid, SpaceLawChangeRuleComponent component,
GameRuleComponent gameRule, GameRuleStartedEvent args)
{
base.Started(uid, component, gameRule, args);

if (!_cfg.GetCVar(NextVars.LRPEnabled))
return;
Comment on lines +40 to +41
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а оно не сделает обьявление ивента, после которого ничего не произойдёт если конфиг отключен?


// Loading a prototype dataset
if (!_prototypeManager.TryIndex<LocalizedDatasetPrototype>(component.LawLocalizedDataset, out var dataset))
{
Logger.Error($"LocalizedDatasetPrototype not found: {component.LawLocalizedDataset}");
return;
}


// Initializing the list of laws if it is empty
if (_sequenceLaws.Count == 0)
{
_sequenceLaws.AddRange(dataset.Values);
}
// Getting active laws from currently active rules
var activeLaws = GetActiveSpaceLaws();

// Excluding active laws from selection
var availableLaws = _sequenceLaws.Except(activeLaws).ToArray();
if (availableLaws.Count == 0)

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / Test Packaging

Operator '==' cannot be applied to operands of type 'method group' and 'int'

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / Test Packaging

Operator '==' cannot be applied to operands of type 'method group' and 'int'

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / YAML Linter

Operator '==' cannot be applied to operands of type 'method group' and 'int'

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / YAML Linter

Operator '==' cannot be applied to operands of type 'method group' and 'int'

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Operator '==' cannot be applied to operands of type 'method group' and 'int'

Check failure on line 61 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Operator '==' cannot be applied to operands of type 'method group' and 'int'
{
availableLaws = _sequenceLaws;

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / Test Packaging

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / Test Packaging

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / YAML Linter

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / YAML Linter

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'

Check failure on line 63 in Content.Server/_CorvaxNext/StationEvents/Events/SpaceLawChange.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string[]'
}

// Selecting a random law from the available ones
var randomLaw = _robustRandom.Pick(availableLaws);
component.RandomMessage = randomLaw;

var stationTime = _gameTiming.CurTime.Subtract(_gameTicker.RoundStartTimeSpan);

var message = Loc.GetString("station-event-space-law-change-announcement",
("essence", Loc.GetString(component.RandomMessage)),
("time", component.AdaptationTime));

var faxMessage = Loc.GetString("station-event-space-law-change-fax-announcement",
("faxEssence", message),
("stationTime", stationTime.ToString("hh\\:mm\\:ss")));

// Sending a global announcement
_chat.DispatchGlobalAnnouncement(message, playSound: true, colorOverride: Color.Gold);
SendSpaceLawChangeFax(faxMessage);

// Start a timer to send a confirmation message after AdaptationTime minutes
Timer.Spawn(TimeSpan.FromMinutes(component.AdaptationTime), () => SendConfirmationMessage(uid));
}

/// <summary>
/// Getting active laws from currently active rules
/// </summary>
private List<string> GetActiveSpaceLaws()
AwareFoxy marked this conversation as resolved.
Show resolved Hide resolved
{
var activeLaws = new List<string>();
foreach (var rule in _gameTicker.GetActiveGameRules())
{
if (_entityManager.TryGetComponent(rule, out SpaceLawChangeRuleComponent? spaceLawComponent))
{
if (!string.IsNullOrEmpty(spaceLawComponent.RandomMessage))
{
activeLaws.Add(spaceLawComponent.RandomMessage);
}
}
}
return activeLaws;
}

/// <summary>
/// Sending a confirmation message about the entry into force of changes in Space Law
/// </summary>
private void SendConfirmationMessage(EntityUid uid)
{
if (!_entityManager.TryGetComponent(uid, out SpaceLawChangeRuleComponent? component) || component.RandomMessage == null)
{
Logger.Error($"Failed to send confirmation message for SpaceLawChangeRule for entity {uid}: Component or RandomMessage is null.");
return;
}

var confirmationMessage = Loc.GetString("station-event-space-law-change-announcement-confirmation", ("essence", Loc.GetString(component.RandomMessage)));
var faxConfirmationMessage = Loc.GetString("station-event-space-law-change-announcement-fax-confirmation", ("faxEssence", confirmationMessage));
_chat.DispatchGlobalAnnouncement(confirmationMessage, playSound: true, colorOverride: Color.Gold);
SendSpaceLawChangeFax(faxConfirmationMessage);
}

/// <summary>
/// Sending a fax announcing changes in Space Law
/// </summary>
private void SendSpaceLawChangeFax(string message)
{
var printout = new FaxPrintout(
message,
Loc.GetString("materials-paper"),
null,
null,
"paper_stamp-centcom",
new List<StampDisplayInfo>
Comment on lines +131 to +135
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Loc.GetString("materials-paper"),
null,
null,
"paper_stamp-centcom",
new List<StampDisplayInfo>
Loc.GetString("materials-paper"),
stampState: "paper_stamp-centcom",
stampedBy: new List<StampDisplayInfo>

по сути должно работать

{
new() { StampedName = Loc.GetString("stamp-component-stamped-name-centcom"), StampedColor = Color.FromHex("#006600") }
});

var faxes = _entityManager.EntityQuery<FaxMachineComponent>();
foreach (var fax in faxes)
{
if (!fax.ReceiveStationGoal)
continue;
_faxSystem.Receive(fax.Owner, printout, Loc.GetString("station-event-space-law-change-fax-sender"), fax);
}
}
}
}
6 changes: 6 additions & 0 deletions Content.Shared/_CorvaxNext/NextVars.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,10 @@ public sealed class NextVars

// public static readonly CVarDef<bool> OfferModeIndicatorsPointShow =
// CVarDef.Create("hud.offer_mode_indicators_point_show", true, CVar.ARCHIVE | CVar.CLIENTONLY);

/// <summary>
/// LRP CVar
/// </summary>
public static readonly CVarDef<bool> LRPEnabled =
CVarDef.Create("lrp.enabled", false, CVar.SERVERONLY);
Comment on lines +45 to +49
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше сделать отдельный цвар для этого ивента, а не общий "лрп"

}
3 changes: 3 additions & 0 deletions Resources/ConfigPresets/Corvax/main.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ time = 180.0
[hub]
advertise = true
tags = "lang:ru,rp:low,rp:med,region:eu_e,tts"

[lrp] # Corvax-Next-LRP
enabled = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
station-event-space-law-change-fax-start = [color=#b8972d]███[/color][color=#1d7a1d]░███░░░░██░░░░[/color][color=#b8972d] ★ ★ ★[/color][color=#1d7a1d]
░██░████░░░██░░░░ [head=3]Бланк документа[/head]
░░█░██░██░░██░█░░ [head=3]NanoTrasen[/head]
░░░░██░░██░██░██░ [bold]ЦК-КОМ[/bold]
░░░░██░░░████░[/color][color=#b8972d]███[/color][color=#b8972d] ★ ★ ★[/color]
==================================================[bold]
УВЕДОМЛЕНИЕ О ИЗМЕНЕНИИ КОРПОРАТИВНОГО ЗАКОНА[/bold]
==================================================
station-event-space-law-change-fax-end =
Слава NanoTrasen!
==================================================[italic]
Место для печати[/italic]

station-event-space-law-change-fax-sender = Центральное Командование


# Уведомление о начале переходного периода
station-event-space-law-change-fax-announcement =
{ station-event-space-law-change-fax-start }
{ $faxEssence }
Продолжительность смены на момент отправки факса: { $stationTime }
{ station-event-space-law-change-fax-end }

station-event-space-law-change-announcement = В связи с последними изменениями в корпоративной политике, { $essence } теперь признается (или признаются) незаконным(-ыми) по кодовому номеру «XX1» Корпоративного закона. В ваших интересах незамедлительно исправить ситуацию до вступления изменений в силу через { $time } минут. Служба безопасности и Командование обязаны приложить все возможные усилия для обеспечения полного соответствия станции требованиям закона к моменту окончания периода адаптации.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
station-event-space-law-change-announcement = В связи с последними изменениями в корпоративной политике, { $essence } теперь признается (или признаются) незаконным(-ыми) по кодовому номеру «XX1» Корпоративного закона. В ваших интересах незамедлительно исправить ситуацию до вступления изменений в силу через { $time } минут. Служба безопасности и Командование обязаны приложить все возможные усилия для обеспечения полного соответствия станции требованиям закона к моменту окончания периода адаптации.
station-event-space-law-change-announcement = В связи с последними изменениями в корпоративной политике, { $essence } теперь признаётся (или признаются) незаконным(-и) по кодовому номеру «XX1» Корпоративного закона. В ваших интересах незамедлительно исправить ситуацию до вступления изменений в силу через { $time } минут. Служба безопасности и Командование обязаны приложить все возможные усилия для обеспечения полного соответствия станции требованиям закона к моменту окончания периода адаптации.



# Уведомление о завершении переходного периода
station-event-space-law-change-announcement-fax-confirmation =
{ station-event-space-law-change-fax-start }
{ $faxEssence }
{ station-event-space-law-change-fax-end }

station-event-space-law-change-announcement-confirmation = Уведомляем вас о вступлении в силу изменений в Корпоративном законе, связанных с недавними изменениями в корпоративной политике. Теперь { $essence } признается (или признаются) незаконным(-ыми) по кодовому номеру «XX1» Корпоративного закона.


# spaceLawChangeLaws localizedDataset
station-event-space-law-change-essence-1 = юбки и шорты
station-event-space-law-change-essence-2 = кухонные ножи
station-event-space-law-change-essence-3 = шляпы и береты
station-event-space-law-change-essence-4 = зимние куртки
station-event-space-law-change-essence-5 = алкогольные напитки
station-event-space-law-change-essence-6 = сигареты
station-event-space-law-change-essence-7 = острая пища
station-event-space-law-change-essence-8 = деятельность руководителей отделов, которые не уделяют должного внимания патриотическому воспитанию своих сотрудников во славу NanoTrasen
AwareFoxy marked this conversation as resolved.
Show resolved Hide resolved
station-event-space-law-change-essence-9 = не ношение головного убора
AwareFoxy marked this conversation as resolved.
Show resolved Hide resolved
station-event-space-law-change-essence-10 = неисполнение главой отдела личного приветствия каждого члена экипажа, посещающего его отдел
AwareFoxy marked this conversation as resolved.
Show resolved Hide resolved
Comment on lines +44 to +46
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

удалить нахуй

station-event-space-law-change-essence-11 = безработица
station-event-space-law-change-essence-12 = обувь
station-event-space-law-change-essence-13 = ведение бумажной документации
station-event-space-law-change-essence-14 = общение не шепотом вне каналов связи
station-event-space-law-change-essence-15 = попытки убедить Капитана станции в существовании мировых заговоров
station-event-space-law-change-essence-16 = введение в оборот фруктов и овощей нового урожая без предварительной дегустации каждого вида Главой персонала
station-event-space-law-change-essence-17 = неисполнение приветствия "Привет, товарищи" при входе в Бриг
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нахуй

station-event-space-law-change-essence-18 = рассказы о событиях, которые противоречат официальным отчетам отдела Службы безопасности
station-event-space-law-change-essence-19 = перерывы
station-event-space-law-change-essence-20 = проведение хирургических операций
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- type: localizedDataset
id: spaceLawChangeLaws
values:
prefix: station-event-space-law-change-essence-
count: 20
14 changes: 14 additions & 0 deletions Resources/Prototypes/_CorvaxNext/GameRules/events.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
- type: entity
id: SpaceLawChange
parent: BaseGameRule
abstract: true
components:
- type: StationEvent
weight: 5
maxOccurrences: 1 # can only happen 1 time per round
duration: null # the rule has to last the whole round
- type: GameRule
minPlayers: 50
- type: SpaceLawChangeRule
lawLocalizedDataset: spaceLawChangeLaws
adaptationTime: 10
Loading