cleaner matching & output for roll command

This commit is contained in:
Valerie Wolfe 2024-03-30 23:37:34 -04:00
parent d4875d06fc
commit 1c6603be0a

View file

@ -5,13 +5,19 @@ namespace Dungeoneer {
public sealed class Command { public sealed class Command {
public static void Roll(IList<string> args) { public static void Roll(IList<string> args) {
// don't do anything with empty expressions
if(args.Count == 0) if(args.Count == 0)
return; return;
var expression = ""; var expression = "";
var diePattern = new Regex(@"\d+d\d+");
// reassemble split args and substitute die notation
foreach(string arg in args) { foreach(string arg in args) {
string part; string part;
if(arg.Contains('d')) {
var dieCheck = diePattern.Match(arg);
if(dieCheck.Success) {
var parts = arg.Split('d'); var parts = arg.Split('d');
var first = parts[0]; var first = parts[0];
var second = parts[1]; var second = parts[1];
@ -26,19 +32,34 @@ namespace Dungeoneer {
return; return;
} }
var result = 0; var rolls = "( ";
for(int i = 0; i < count; i++) for(int i = 0; i < count; i++) {
result += Util.Roll(sides); string result;
part = result.ToString(); var roll = Util.Roll(sides);
if(i < count - 1)
result = $"{roll} + ";
else
result = $"{roll} ";
rolls += result;
}
rolls += ")";
part = rolls;
} else } else
part = arg; part = arg;
expression += $"{part} "; expression += $"{part} ";
} }
dynamic output = Scripting.Expr($"eval('{expression}')"); dynamic output;
try { output = Scripting.Expr($"eval('{expression}')"); }
catch {
Console.WriteLine("invalid expression");
return;
}
Console.WriteLine($"{expression}\n=> {output}"); Console.WriteLine($"{expression}\n=> {output}");
} }
} }
} }