Files
tbd-station-14/Content.Server/Speech/EntitySystems/PirateAccentSystem.cs
Pieter-Jan Briers 4a2a63a86b Cache regex instances in most cases (#27699)
Using static Regex functions that take in a pattern is bad because the pattern constantly needs to be re-parsed. With https://github.com/space-wizards/RobustToolbox/pull/5107, the engine has an analyzer to warn for this practice now.

This commit brings most of content up to snuff already, though some of the tricker code I left for somebody else.
2024-05-06 08:57:32 +10:00

50 lines
1.7 KiB
C#

using System.Linq;
using Content.Server.Speech.Components;
using Robust.Shared.Random;
using System.Text.RegularExpressions;
namespace Content.Server.Speech.EntitySystems;
public sealed class PirateAccentSystem : EntitySystem
{
private static readonly Regex FirstWordAllCapsRegex = new(@"^(\S+)");
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly ReplacementAccentSystem _replacement = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PirateAccentComponent, AccentGetEvent>(OnAccentGet);
}
// converts left word when typed into the right word. For example typing you becomes ye.
public string Accentuate(string message, PirateAccentComponent component)
{
var msg = _replacement.ApplyReplacements(message, "pirate");
if (!_random.Prob(component.YarrChance))
return msg;
//Checks if the first word of the sentence is all caps
//So the prefix can be allcapped and to not resanitize the captial
var firstWordAllCaps = !FirstWordAllCapsRegex.Match(msg).Value.Any(char.IsLower);
var pick = _random.Pick(component.PirateWords);
var pirateWord = Loc.GetString(pick);
// Reverse sanitize capital
if (!firstWordAllCaps)
msg = msg[0].ToString().ToLower() + msg.Remove(0, 1);
else
pirateWord = pirateWord.ToUpper();
msg = pirateWord + " " + msg;
return msg;
}
private void OnAccentGet(EntityUid uid, PirateAccentComponent component, AccentGetEvent args)
{
args.Message = Accentuate(args.Message, component);
}
}