81 lines
3.0 KiB
C#
81 lines
3.0 KiB
C#
using System.Text.RegularExpressions;
|
|
|
|
using MultiversalDiplomacy.Model;
|
|
using MultiversalDiplomacy.Orders;
|
|
|
|
namespace MultiversalDiplomacy.Script;
|
|
|
|
public class GameScriptHandler(World world, bool strict = false) : IScriptHandler
|
|
{
|
|
public string Prompt => "orders> ";
|
|
|
|
public World World { get; private set; } = world;
|
|
|
|
/// <summary>
|
|
/// Whether unsuccessful commands should terminate the script.
|
|
/// </summary>
|
|
public bool Strict { get; } = strict;
|
|
|
|
private string? CurrentPower = null;
|
|
|
|
public IScriptHandler? HandleInput(string input)
|
|
{
|
|
if (input == "") {
|
|
CurrentPower = null;
|
|
return this;
|
|
}
|
|
if (input.StartsWith('#')) return this;
|
|
|
|
// "---" submits the orders and allows queries about the outcome
|
|
if (input == "---") {
|
|
Console.WriteLine("Submitting orders for adjudication");
|
|
// TODO submit, validate, and adjudicate orders
|
|
// TODO pass validation, adjudication, and prev/next World to next handler
|
|
return new AdjudicationQueryScriptHandler(World, Strict);
|
|
}
|
|
|
|
// "===" submits the orders and moves immediately to taking the next set of orders
|
|
// i.e. it's "---" twice
|
|
if (input == "===") {
|
|
Console.WriteLine("Submitting orders for adjudication");
|
|
// TODO submit, validate, and adjudicate orders
|
|
// TODO replace World with updated world and return a new handler
|
|
Console.WriteLine("Ready for orders");
|
|
return new GameScriptHandler(World, Strict);
|
|
}
|
|
|
|
// A block of orders for a single power beginning with "{name}:"
|
|
if (World.Powers.FirstOrDefault(p => input.EqualsAnyCase($"{p}:"), null) is string power) {
|
|
CurrentPower = power;
|
|
return this;
|
|
}
|
|
|
|
// If it's not a comment, submit, or order block, assume it's an order.
|
|
string orderPower;
|
|
string orderText;
|
|
if (CurrentPower is not null) {
|
|
// In a block of orders from a power, the power was specified at the top and each line is an order.
|
|
orderPower = CurrentPower;
|
|
orderText = input;
|
|
} else {
|
|
// Outside a power block, the power is prefixed to each order.
|
|
Regex re = new($"^{World.Map.PowerRegex}(?:[:])? (.*)$", RegexOptions.IgnoreCase);
|
|
var match = re.Match(input);
|
|
if (!match.Success) {
|
|
Console.WriteLine($"Could not determine ordering power in \"{input}\"");
|
|
return Strict ? null : this;
|
|
}
|
|
orderPower = match.Groups[1].Value;
|
|
orderText = match.Groups[2].Value;
|
|
}
|
|
|
|
if (OrderParser.TryParseOrder(World, orderPower, orderText, out Order? order)) {
|
|
Console.WriteLine($"Parsed {orderPower} order \"{orderText}\" but doing anything with it isn't implemented yet");
|
|
return this;
|
|
}
|
|
|
|
Console.WriteLine($"Failed to parse \"{orderText}\"");
|
|
return Strict ? null : this;
|
|
}
|
|
}
|