|
| 1 | +// FuzzTable.cs |
| 2 | +// |
| 3 | +using System; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | + |
| 6 | +namespace DiscordBot.Data; |
| 7 | + |
| 8 | +public class FuzzTable |
| 9 | +{ |
| 10 | + private static Random random = new(); |
| 11 | + private static Regex parenContents = null; |
| 12 | + private static TimeSpan timeout = new(10*10000/*x10nanoseconds*/); |
| 13 | + |
| 14 | + //TODO: an instance keeps an array of alternates and an MRU list |
| 15 | + |
| 16 | + // Evaluate a single fuzz string. |
| 17 | + // "(He|She|They) (picked|selected) a (green|red|blue) (ball|block)." |
| 18 | + // "She picked a red ball." |
| 19 | + // Replace any parenthetical phrase with one of its choices at random. |
| 20 | + // Allows for nesting of choices. There's currently no way to escape |
| 21 | + // parentheses or vertical bars so strings must not include strays. |
| 22 | + // Returns one permutation from all choice alternatives given. |
| 23 | + // Does not remember what choices were given. |
| 24 | + // |
| 25 | + public static string Evaluate(string fuzz) |
| 26 | + { |
| 27 | + if (string.IsNullOrEmpty(fuzz)) |
| 28 | + return ""; |
| 29 | + if (parenContents == null) |
| 30 | + parenContents = |
| 31 | + new(@"\( ( [^(]*? ) \)", |
| 32 | + RegexOptions.IgnorePatternWhitespace | |
| 33 | + RegexOptions.Compiled, |
| 34 | + timeout); |
| 35 | + string before = null; |
| 36 | + while (fuzz != before) |
| 37 | + { |
| 38 | + before = fuzz; |
| 39 | + try |
| 40 | + { |
| 41 | + fuzz = parenContents.Replace(fuzz, |
| 42 | + (m) => PickAlternate(m.Groups[1].ToString())); |
| 43 | + } |
| 44 | + catch (RegexMatchTimeoutException) |
| 45 | + { |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | + return fuzz; |
| 50 | + } |
| 51 | + |
| 52 | + private static string PickAlternate(string fuzz) |
| 53 | + { |
| 54 | + if (string.IsNullOrEmpty(fuzz)) |
| 55 | + return ""; |
| 56 | + string[] alternates = fuzz.Split('|'); |
| 57 | + if (alternates == null || alternates.Length == 0) |
| 58 | + return ""; |
| 59 | + int pick = random.Next(0, alternates.Length); |
| 60 | + return alternates[pick]; |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments