Compare commits

..

No commits in common. "f02e71d4f94f23af529d6b1ab11b03963e06cc93" and "512c91d2de67d17ade5d71d62cd99da6cd090c88" have entirely different histories.

4 changed files with 68 additions and 162 deletions

View File

@ -34,22 +34,14 @@ public class OrderParser(World world)
public const string ViaConvoy = "(convoy|via convoy|by convoy)"; public const string ViaConvoy = "(convoy|via convoy|by convoy)";
public Regex UnitDeclaration = new( public Regex PowerCommand = new($"^{world.Map.PowerRegex}(?:[:])? (.*)$");
$"^{world.Map.PowerRegex} {Type} {world.Map.ProvinceRegex}(?:{SlashLocation}|{ParenLocation})?$",
RegexOptions.IgnoreCase);
public static ( public static (
string power, string power,
string type, string command)
string province, ParsePowerCommand(Match match) => (
string location)
ParseUnitDeclaration(Match match) => (
match.Groups[1].Value, match.Groups[1].Value,
match.Groups[2].Value, match.Groups[2].Value);
match.Groups[3].Value,
match.Groups[4].Value.Length > 0
? match.Groups[4].Value
: match.Groups[5].Value);
public Regex Hold => new( public Regex Hold => new(
$"^{UnitSpec} {HoldVerb}$", $"^{UnitSpec} {HoldVerb}$",
@ -186,29 +178,27 @@ public class OrderParser(World world)
public static bool TryParseUnit(World world, string unitSpec, [NotNullWhen(true)] out Unit? newUnit) public static bool TryParseUnit(World world, string unitSpec, [NotNullWhen(true)] out Unit? newUnit)
{ {
newUnit = null; newUnit = null;
OrderParser re = new(world);
Match match = re.UnitDeclaration.Match(unitSpec); Regex reUnit = new(
if (!match.Success) return false; $"^{world.Map.PowerRegex} {Type} {world.Map.ProvinceRegex}(?:{SlashLocation}|{ParenLocation})?$");
var unit = ParseUnitDeclaration(match); Match match = reUnit.Match(unitSpec);
if (!match.Success) {
return false;
}
string power = world.Map.Powers.First(p => p.EqualsAnyCase(unit.power)); string power = world.Map.Powers.First(p => p.EqualsAnyCase(match.Groups[1].Value));
string typeName = Enum.GetNames<UnitType>().First(name => name.StartsWithAnyCase(unit.type)); string typeName = Enum.GetNames<UnitType>().First(name => name.StartsWithAnyCase(match.Groups[2].Value));
UnitType type = Enum.Parse<UnitType>(typeName); UnitType type = Enum.Parse<UnitType>(typeName);
Province province = world.Map.Provinces.First(prov => prov.Is(unit.province)); Province province = world.Map.Provinces.First(prov
Location? location; => prov.Name.EqualsAnyCase(match.Groups[3].Value)
if (unit.location.Length > 0) { || prov.Abbreviations.Any(abv => abv.EqualsAnyCase(match.Groups[3].Value)));
location = province.Locations.FirstOrDefault(loc => loc!.Is(unit.location), null);
} else { string locationName = match.Groups[4].Length > 0 ? match.Groups[4].Value : match.Groups[5].Value;
location = type switch { Location location = province.Locations.First(loc
UnitType.Army => province.Locations.FirstOrDefault(loc => loc.Type == LocationType.Land), => loc.Name.StartsWithAnyCase(locationName)
UnitType.Fleet => province.Locations.FirstOrDefault(loc => loc.Type == LocationType.Water), || loc.Abbreviation.StartsWithAnyCase(locationName));
_ => null,
};
}
if (location is null) return false;
newUnit = Unit.Build(location.Key, Season.First, power, type); newUnit = Unit.Build(location.Key, Season.First, power, type);
return true; return true;
@ -223,77 +213,73 @@ public class OrderParser(World world)
} else if (re.Move.Match(command) is Match moveMatch && moveMatch.Success) { } else if (re.Move.Match(command) is Match moveMatch && moveMatch.Success) {
return TryParseMoveOrder(world, power, moveMatch, out order); return TryParseMoveOrder(world, power, moveMatch, out order);
} else if (re.SupportHold.Match(command) is Match sholdMatch && sholdMatch.Success) { } else if (re.SupportHold.Match(command) is Match sholdMatch && sholdMatch.Success) {
return TryParseSupportHoldOrder(world, power, sholdMatch, out order); // DATC 4.B.4: coast specification in support orders
throw new NotImplementedException();
} else if (re.SupportMove.Match(command) is Match smoveMatch && smoveMatch.Success) { } else if (re.SupportMove.Match(command) is Match smoveMatch && smoveMatch.Success) {
return TryParseSupportMoveOrder(world, power, smoveMatch, out order); throw new NotImplementedException();
} else { } else {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
public static bool TryParseOrderSubject( public static bool TryParseHoldOrder(World world, string power, Match match, [NotNullWhen(true)] out Order? order)
World world,
string parsedTimeline,
string parsedTurn,
string parsedProvince,
[NotNullWhen(true)] out Unit? subject)
{ {
subject = null; order = null;
var hold = ParseHold(match);
string timeline = parsedTimeline.Length > 0 string timeline = hold.timeline.Length > 0
? parsedTimeline ? hold.timeline
// If timeline is unspecified, use the root timeline // If timeline is unspecified, use the root timeline
: Season.First.Timeline; : Season.First.Timeline;
var seasonsInTimeline = world.Timelines.Seasons.Where(season => season.Timeline == timeline); var seasonsInTimeline = world.Timelines.Seasons.Where(season => season.Timeline == timeline);
if (!seasonsInTimeline.Any()) return false; if (!seasonsInTimeline.Any()) return false;
int turn = parsedTurn.Length > 0 int turn = hold.turn.Length > 0
? int.Parse(parsedTurn) ? int.Parse(hold.turn)
// If turn is unspecified, use the latest turn in the timeline // If turn is unspecified, use the latest turn in the timeline
: seasonsInTimeline.Max(season => season.Turn); : seasonsInTimeline.Max(season => season.Turn);
Province province = world.Map.Provinces.Single(province => province.Is(parsedProvince)); Province province = world.Map.Provinces.Single(province => province.Is(hold.province));
// Because only one unit can be in a province at a time, the province is sufficient to identify the subject Unit? subject = world.Units.FirstOrDefault(unit
// and the location is ignored. This also satisfies DATC 4.B.5, which requires that a wrong coast for the
// subject be ignored.
subject = world.Units.FirstOrDefault(unit
=> world.Map.GetLocation(unit!.Location).ProvinceName == province.Name => world.Map.GetLocation(unit!.Location).ProvinceName == province.Name
&& unit!.Season.Timeline == timeline && unit!.Season.Timeline == timeline
&& unit!.Season.Turn == turn, && unit!.Season.Turn == turn,
null); null);
return subject is not null; if (subject is null) return false;
}
public static bool TryParseHoldOrder(
World world,
string power,
Match match,
[NotNullWhen(true)] out Order? order)
{
order = null;
var hold = ParseHold(match);
if (!TryParseOrderSubject(world, hold.timeline, hold.turn, hold.province, out Unit? subject)) {
return false;
}
order = new HoldOrder(power, subject); order = new HoldOrder(power, subject);
return true; return true;
} }
public static bool TryParseMoveOrder( public static bool TryParseMoveOrder(World world, string power, Match match, [NotNullWhen(true)] out Order? order)
World world,
string power,
Match match,
[NotNullWhen(true)] out Order? order)
{ {
order = null; order = null;
var move = ParseMove(match); var move = ParseMove(match);
if (!TryParseOrderSubject(world, move.timeline, move.turn, move.province, out Unit? subject)) { string timeline = move.timeline.Length > 0
return false; ? move.timeline
} // If timeline is unspecified, use the root timeline
: Season.First.Timeline;
var seasonsInTimeline = world.Timelines.Seasons.Where(season => season.Timeline == timeline);
if (!seasonsInTimeline.Any()) return false;
int turn = move.turn.Length > 0
? int.Parse(move.turn)
// If turn is unspecified, use the latest turn in the timeline
: seasonsInTimeline.Max(season => season.Turn);
Province province = world.Map.Provinces.Single(province => province.Is(move.province));
// Because only one unit can be in a province at a time, the province is sufficient to identify the subject
// and the location is ignored. This also satisfies DATC 4.B.5, which requires that a wrong coast for the
// subject be ignored.
Unit? subject = world.Units.FirstOrDefault(unit
=> world.Map.GetLocation(unit!.Location).ProvinceName == province.Name
&& unit!.Season.Timeline == timeline
&& unit!.Season.Turn == turn,
null);
if (subject is null) return false;
string destTimeline = move.destTimeline.Length > 0 string destTimeline = move.destTimeline.Length > 0
? move.destTimeline ? move.destTimeline
@ -337,29 +323,4 @@ public class OrderParser(World world)
order = new MoveOrder(power, subject, new(destTimeline, destTurn), destLocationKey); order = new MoveOrder(power, subject, new(destTimeline, destTurn), destLocationKey);
return true; return true;
} }
public static bool TryParseSupportHoldOrder(
World world,
string power,
Match match,
[NotNullWhen(true)] out Order? order)
{
order = null;
var support = ParseSupportHold(match);
throw new NotImplementedException();
}
public static bool TryParseSupportMoveOrder(
World world,
string power,
Match match,
[NotNullWhen(true)] out Order? order)
{
order = null;
var support = ParseSupportMove(match);
throw new NotImplementedException();
// It is possible to support a move to an inaccessible coast if another coast is accessible to the subject.
// DATC 4.B.4 prefers that automatic adjudicators strictly require matching coasts in supports.
}
} }

View File

@ -1,6 +1,5 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using MultiversalDiplomacy.Adjudicate;
using MultiversalDiplomacy.Model; using MultiversalDiplomacy.Model;
using MultiversalDiplomacy.Orders; using MultiversalDiplomacy.Orders;
@ -17,9 +16,7 @@ public class GameScriptHandler(World world, bool strict = false) : IScriptHandle
/// </summary> /// </summary>
public bool Strict { get; } = strict; public bool Strict { get; } = strict;
private string? CurrentPower { get; set; } = null; private string? CurrentPower = null;
public List<Order> Orders { get; } = [];
public IScriptHandler? HandleInput(string input) public IScriptHandler? HandleInput(string input)
{ {
@ -32,31 +29,19 @@ public class GameScriptHandler(World world, bool strict = false) : IScriptHandle
// "---" submits the orders and allows queries about the outcome // "---" submits the orders and allows queries about the outcome
if (input == "---") { if (input == "---") {
Console.WriteLine("Submitting orders for adjudication"); Console.WriteLine("Submitting orders for adjudication");
var adjudicator = MovementPhaseAdjudicator.Instance; // TODO submit, validate, and adjudicate orders
var validation = adjudicator.ValidateOrders(World, Orders); // TODO pass validation, adjudication, and prev/next World to next handler
var validOrders = validation return new AdjudicationQueryScriptHandler(World, Strict);
.Where(v => v.Valid)
.Select(v => v.Order)
.ToList();
var adjudication = adjudicator.AdjudicateOrders(World, validOrders);
var newWorld = adjudicator.UpdateWorld(World, adjudication);
return new AdjudicationQueryScriptHandler(newWorld, Strict);
} }
// "===" submits the orders and moves immediately to taking the next set of orders // "===" submits the orders and moves immediately to taking the next set of orders
// i.e. it's "---" twice // i.e. it's "---" twice
if (input == "===") { if (input == "===") {
Console.WriteLine("Submitting orders for adjudication"); Console.WriteLine("Submitting orders for adjudication");
var adjudicator = MovementPhaseAdjudicator.Instance; // TODO submit, validate, and adjudicate orders
var validation = adjudicator.ValidateOrders(World, Orders); // TODO replace World with updated world and return a new handler
var validOrders = validation
.Where(v => v.Valid)
.Select(v => v.Order)
.ToList();
var adjudication = adjudicator.AdjudicateOrders(World, validOrders);
World = adjudicator.UpdateWorld(World, adjudication);
Console.WriteLine("Ready for orders"); Console.WriteLine("Ready for orders");
return this; return new GameScriptHandler(World, Strict);
} }
// A block of orders for a single power beginning with "{name}:" // A block of orders for a single power beginning with "{name}:"
@ -85,8 +70,7 @@ public class GameScriptHandler(World world, bool strict = false) : IScriptHandle
} }
if (OrderParser.TryParseOrder(World, orderPower, orderText, out Order? order)) { if (OrderParser.TryParseOrder(World, orderPower, orderText, out Order? order)) {
Console.WriteLine($"Parsed {orderPower} order: {order}"); Console.WriteLine($"Parsed {orderPower} order \"{orderText}\" but doing anything with it isn't implemented yet");
Orders.Add(order);
return this; return this;
} }

View File

@ -1,7 +1,6 @@
using NUnit.Framework; using NUnit.Framework;
using MultiversalDiplomacy.Model; using MultiversalDiplomacy.Model;
using MultiversalDiplomacy.Orders;
using MultiversalDiplomacy.Script; using MultiversalDiplomacy.Script;
namespace MultiversalDiplomacyTests; namespace MultiversalDiplomacyTests;
@ -17,7 +16,7 @@ public class ReplTest
repl[""" repl["""
unit Germany A Munich unit Germany A Munich
unit Austria Army Tyrolia unit Austria Army Tyrolia
unit England F Lon unit England F London
"""].Ready(); """].Ready();
Assert.That(repl.Handler, Is.TypeOf<SetupScriptHandler>()); Assert.That(repl.Handler, Is.TypeOf<SetupScriptHandler>());
@ -33,42 +32,4 @@ public class ReplTest
Assert.That(repl.Handler, Is.TypeOf<GameScriptHandler>()); Assert.That(repl.Handler, Is.TypeOf<GameScriptHandler>());
} }
[Test]
public void SubmitOrders()
{
SetupScriptHandler setup = new(World.WithStandardMap(), strict: true);
ReplDriver repl = new ReplDriver(setup)["""
unit Germany A Mun
unit Austria A Tyr
unit England F Lon
begin
"""];
repl["""
Germany A Mun hold
Austria: Army Tyrolia - Vienna
England:
Lon h
"""].Ready();
Assert.That(repl.Handler, Is.TypeOf<GameScriptHandler>());
GameScriptHandler handler = (GameScriptHandler)repl.Handler!;
Assert.That(handler.Orders.Count, Is.EqualTo(3));
Assert.That(handler.Orders.Single(o => o.Power == "Germany"), Is.TypeOf<HoldOrder>());
Assert.That(handler.Orders.Single(o => o.Power == "Austria"), Is.TypeOf<MoveOrder>());
Assert.That(handler.Orders.Single(o => o.Power == "England"), Is.TypeOf<HoldOrder>());
Assert.That(handler.World.Timelines.Pasts.Count, Is.EqualTo(1));
World before = handler.World;
repl["""
---
"""].Ready();
Assert.That(repl.Handler, Is.TypeOf<AdjudicationQueryScriptHandler>());
var newHandler = (AdjudicationQueryScriptHandler)repl.Handler!;
Assert.That(newHandler.World, Is.Not.EqualTo(before));
Assert.That(newHandler.World.Timelines.Pasts.Count, Is.EqualTo(2));
}
} }

View File

@ -6,7 +6,7 @@ In lieu of a systematic overview of the architecture, here are a few scattered n
The data model here is based on the data model of [godip](https://github.com/zond/godip). In particular, godip handles the distinction between army and fleet movement by distinguishing between Provicnces and SubProvinces, which 5dplomacy calls Locations. The graph edges that define valid paths are drawn between Locations, but occupation by a unit and being a supply center are properties of the Province as a whole. This makes it easy to represent the different paths available to armies or fleets: the land and sea graphs are unconnected and only interact at the Province level. This also provides a way to distinguish the connectivity of multiple coasts within a province. The data model here is based on the data model of [godip](https://github.com/zond/godip). In particular, godip handles the distinction between army and fleet movement by distinguishing between Provicnces and SubProvinces, which 5dplomacy calls Locations. The graph edges that define valid paths are drawn between Locations, but occupation by a unit and being a supply center are properties of the Province as a whole. This makes it easy to represent the different paths available to armies or fleets: the land and sea graphs are unconnected and only interact at the Province level. This also provides a way to distinguish the connectivity of multiple coasts within a province.
As a consequence of the unconnected land and sea graphs, there is no fundamental difference between army movement and fleet movement, since the inability of armies to move into the ocean is ensured by the lack of edges between land and sea locations. Unit type still remains significant with respect to convoys, since only fleets can convoy and only armies can be convoyed. Unit type is also relevant to the interpretation of orders that do not fully specify location. And, of course, unit type matters to how clients represent the units. As a consequence of the unconnected land and sea graphs, there is no special significance to unit type in movement, since the inability of fleets to move to land locations is ensured by the lack of edges from land locations to sea locations. The primary difference between unit types becomes "can convoy" and "can move by convoy", as well as how the units are represented by clients.
Internally, land locations are named "land" or "l" and water locations are called "water" or "w". For example, SPA has three locations: SPA/nc, SPA/sc, and SPA/l. This provides a uniform way to handle unit location, because locations in orders without coast specifications can easily be inferred from the map and the unit type. For example, "A Mun - Tyr" can easily be inferred to mean "A Mun/l - Tyr/l" because A Mun is located in the "land" location in Mun and the "land" location in Tyr is the only connected one. Internally, land locations are named "land" or "l" and water locations are called "water" or "w". For example, SPA has three locations: SPA/nc, SPA/sc, and SPA/l. This provides a uniform way to handle unit location, because locations in orders without coast specifications can easily be inferred from the map and the unit type. For example, "A Mun - Tyr" can easily be inferred to mean "A Mun/l - Tyr/l" because A Mun is located in the "land" location in Mun and the "land" location in Tyr is the only connected one.