improved roll command

This commit is contained in:
Valerie Wolfe 2024-03-30 01:51:02 -04:00
parent 94c401e85c
commit d4875d06fc
2 changed files with 34 additions and 48 deletions

View file

@ -1,55 +1,42 @@
using System.Text.RegularExpressions;
namespace Dungeoneer { namespace Dungeoneer {
public sealed class Command { public sealed class Command {
public static void Roll(IList<string> args) { public static void Roll(IList<string> args) {
var argc = args.Count; if(args.Count == 0)
if(argc == 1) {
if(args[0].Contains("d")) {
var parts = args[0].Split('d');
Roll(new List<string> { parts[1], parts[0] });
return; return;
} var expression = "";
var arg = args[0];
int sides; foreach(string arg in args) {
try { sides = int.Parse(arg); } string part;
catch(Exception _) { if(arg.Contains('d')) {
Console.WriteLine($"'{arg}' is not a number"); var parts = arg.Split('d');
return; var first = parts[0];
} var second = parts[1];
var result = Dungeoneer.Util.Roll(sides);
Console.WriteLine($" -> {result}");
} else if(argc == 2) {
var result = 0;
var first = args[0];
int sides;
try { sides = int.Parse(first); }
catch(Exception _) {
Console.WriteLine($"'{first}' is not a number");
return;
}
var second = args[1];
int count; int count;
try { count = int.Parse(second); } int sides;
catch(Exception _) { try {
Console.WriteLine($"'{second}' is not a number"); count = int.Parse(first);
return; sides = int.Parse(second);
} } catch {
if(count == 1) { Console.WriteLine("'{arg}' is not a valid dice expression");
Roll(new List<string> { first });
return; return;
} }
var work = ""; var result = 0;
for(int _ = 0; _ < count; _++) { for(int i = 0; i < count; i++)
var roll = Dungeoneer.Util.Roll(sides); result += Util.Roll(sides);
result += roll; part = result.ToString();
work += $"{roll} ";
}
Console.WriteLine($"{work}\n -> {result}");
} else } else
Console.WriteLine($"'roll' accepts 1 or 2 arguments ({argc} given)"); part = arg;
expression += $"{part} ";
}
dynamic output = Scripting.Expr($"eval('{expression}')");
Console.WriteLine($"{expression}\n=> {output}");
} }
} }

View file

@ -28,9 +28,8 @@ namespace Dungeoneer {
Scope.roll = (Func<int, int>)Dungeoneer.Util.Roll; Scope.roll = (Func<int, int>)Dungeoneer.Util.Roll;
} }
public static void Run(string file) { public static void Run(string file) { Engine.ExecuteFile(file, Scope); }
Engine.ExecuteFile(file, Scope); public static dynamic Expr(string expression) { return Engine.Execute(expression, Scope); }
}
public static string Input(string prompt) { public static string Input(string prompt) {
Console.Write(prompt); Console.Write(prompt);