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 static void Roll(IList<string> args) {
// don't do anything with empty expressions
if(args.Count == 0)
return;
var expression = "";
var diePattern = new Regex(@"\d+d\d+");
// reassemble split args and substitute die notation
foreach(string arg in args) {
string part;
if(arg.Contains('d')) {
var dieCheck = diePattern.Match(arg);
if(dieCheck.Success) {
var parts = arg.Split('d');
var first = parts[0];
var second = parts[1];
@ -26,19 +32,34 @@ namespace Dungeoneer {
return;
}
var result = 0;
for(int i = 0; i < count; i++)
result += Util.Roll(sides);
part = result.ToString();
var rolls = "( ";
for(int i = 0; i < count; i++) {
string result;
var roll = Util.Roll(sides);
if(i < count - 1)
result = $"{roll} + ";
else
result = $"{roll} ";
rolls += result;
}
rolls += ")";
part = rolls;
} else
part = arg;
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}");
}
}
}