66 lines
1.3 KiB
C#
66 lines
1.3 KiB
C#
using System.Text.RegularExpressions;
|
|
|
|
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;
|
|
|
|
var dieCheck = diePattern.Match(arg);
|
|
if(dieCheck.Success) {
|
|
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;
|
|
} else
|
|
part = arg;
|
|
expression += $"{part} ";
|
|
}
|
|
|
|
dynamic output;
|
|
try { output = Scripting.Expr($"eval('{expression}')"); }
|
|
catch {
|
|
Console.WriteLine("invalid expression");
|
|
return;
|
|
}
|
|
Console.WriteLine($"{expression}\n=> {output}");
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|