Implement regex order parsing in game script handler

This commit is contained in:
Tim Van Baak 2024-08-21 13:46:02 +00:00
parent 8e976433c8
commit 2745d12d29
1 changed files with 37 additions and 3 deletions

View File

@ -1,10 +1,13 @@
using System.Text.RegularExpressions;
using MultiversalDiplomacy.Model; using MultiversalDiplomacy.Model;
using MultiversalDiplomacy.Orders;
namespace MultiversalDiplomacy.Script; namespace MultiversalDiplomacy.Script;
public class GameScriptHandler(World world, bool strict = false) : IScriptHandler public class GameScriptHandler(World world, bool strict = false) : IScriptHandler
{ {
public string Prompt => "game> "; public string Prompt => "orders> ";
public World World { get; private set; } = world; public World World { get; private set; } = world;
@ -22,7 +25,7 @@ public class GameScriptHandler(World world, bool strict = false) : IScriptHandle
return this; return this;
} }
// --- submits the orders for validation to allow for assertions about it // "---" submits the orders for validation to allow for assertions about it
if (input == "---") { if (input == "---") {
// TODO submit orders // TODO submit orders
// TODO return a new handler that handles asserts // TODO return a new handler that handles asserts
@ -34,10 +37,41 @@ public class GameScriptHandler(World world, bool strict = false) : IScriptHandle
return this; return this;
} }
// TODO parse order, including "{power} {order}" for one-offs if (TryParseOrder(input, out Order? order)) {
Console.WriteLine($"Parsed order \"{input}\" but doing anything with it isn't implemented yet");
} else if (Strict) {
return null;
}
Console.WriteLine($"{CurrentPower}: {input}"); Console.WriteLine($"{CurrentPower}: {input}");
return this; return this;
} }
private bool TryParseOrder(string input, out Order? order) {
order = null;
OrderRegex re = new(World);
Match match;
if ((match = re.Hold.Match(input)).Success) {
var hold = OrderRegex.ParseHold(match);
string power = hold.power.Length > 0 ? hold.power : CurrentPower ?? hold.power;
Unit unit = World.Units.First(unit
=> World.Map.GetLocation(unit.Location).ProvinceName == hold.province
&& unit.Season.Timeline == (hold.timeline.Length > 0 ? hold.timeline : "a")
&& unit.Season.Turn.ToString() == (hold.turn.Length > 0 ? hold.turn : "0"));
order = new HoldOrder(power, unit);
return true;
} else if ((match = re.Move.Match(input)).Success) {
var move = OrderRegex.ParseMove(match);
Unit unit = World.Units.First(unit
=> World.Map.GetLocation(unit.Location).ProvinceName == move.province
&& unit.Season.Timeline == (move.timeline.Length > 0 ? move.timeline : "a")
&& unit.Season.Turn.ToString() == (move.turn.Length > 0 ? move.turn : "0"));
order = new MoveOrder(move.power, unit, Season.First, "l");
return true;
}
Console.WriteLine($"Failed to parse \"{input}\"");
return false;
}
} }