From d4875d06fce54d51dee415a9785028125da4991a Mon Sep 17 00:00:00 2001 From: Valerie Date: Sat, 30 Mar 2024 01:51:02 -0400 Subject: [PATCH] improved roll command --- Command.cs | 77 ++++++++++++++++++++++------------------------------ Scripting.cs | 5 ++-- 2 files changed, 34 insertions(+), 48 deletions(-) diff --git a/Command.cs b/Command.cs index 6117ccc..462f0f9 100644 --- a/Command.cs +++ b/Command.cs @@ -1,55 +1,42 @@ +using System.Text.RegularExpressions; namespace Dungeoneer { public sealed class Command { public static void Roll(IList args) { - var argc = args.Count; - if(argc == 1) { - if(args[0].Contains("d")) { - var parts = args[0].Split('d'); - Roll(new List { parts[1], parts[0] }); - return; - } - var arg = args[0]; - int sides; - try { sides = int.Parse(arg); } - catch(Exception _) { - Console.WriteLine($"'{arg}' is not a number"); - return; - } - 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; - try { count = int.Parse(second); } - catch(Exception _) { - Console.WriteLine($"'{second}' is not a number"); - return; - } - if(count == 1) { - Roll(new List { first }); - return; - } + if(args.Count == 0) + return; + var expression = ""; - var work = ""; - for(int _ = 0; _ < count; _++) { - var roll = Dungeoneer.Util.Roll(sides); - result += roll; - work += $"{roll} "; - } - Console.WriteLine($"{work}\n -> {result}"); - } else - Console.WriteLine($"'roll' accepts 1 or 2 arguments ({argc} given)"); + foreach(string arg in args) { + string part; + if(arg.Contains('d')) { + 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 result = 0; + for(int i = 0; i < count; i++) + result += Util.Roll(sides); + part = result.ToString(); + } else + part = arg; + expression += $"{part} "; + } + + dynamic output = Scripting.Expr($"eval('{expression}')"); + Console.WriteLine($"{expression}\n=> {output}"); } } diff --git a/Scripting.cs b/Scripting.cs index a6f6561..dad4064 100644 --- a/Scripting.cs +++ b/Scripting.cs @@ -28,9 +28,8 @@ namespace Dungeoneer { Scope.roll = (Func)Dungeoneer.Util.Roll; } - public static void Run(string file) { - Engine.ExecuteFile(file, Scope); - } + public static void Run(string file) { Engine.ExecuteFile(file, Scope); } + public static dynamic Expr(string expression) { return Engine.Execute(expression, Scope); } public static string Input(string prompt) { Console.Write(prompt);