dungeoneer-cs/Command.cs

67 lines
1.3 KiB
C#
Raw Normal View History

2024-03-30 01:51:02 -04:00
using System.Text.RegularExpressions;
namespace Dungeoneer {
public sealed class Command {
public static void Roll(IList<string> args) {
// don't do anything with empty expressions
2024-03-30 01:51:02 -04:00
if(args.Count == 0)
return;
var expression = "";
var diePattern = new Regex(@"\d+d\d+");
// reassemble split args and substitute die notation
2024-03-30 01:51:02 -04:00
foreach(string arg in args) {
string part;
var dieCheck = diePattern.Match(arg);
if(dieCheck.Success) {
2024-03-30 01:51:02 -04:00
var parts = arg.Split('d');
var first = parts[0];
var second = parts[1];
int count;
int sides;
try {
count = int.Parse(first);
sides = int.Parse(second);
} catch {
Console.WriteLine("'{arg}' is not a valid dice expression");
return;
}
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;
2024-03-30 01:51:02 -04:00
} else
part = arg;
expression += $"{part} ";
}
dynamic output;
try { output = Scripting.Expr($"eval('{expression}')"); }
catch {
Console.WriteLine("invalid expression");
return;
}
2024-03-30 01:51:02 -04:00
Console.WriteLine($"{expression}\n=> {output}");
}
}
}