updating unit movement

This commit is contained in:
hz
2026-05-19 14:58:51 -05:00
parent 762143918b
commit da61ec8bf4
7 changed files with 281 additions and 23 deletions
@@ -160,7 +160,7 @@ public class UnitTrainingService
if (!await CanMoveToAsync(username, request.ToQ, request.ToR))
{
throw new InvalidOperationException("Archers can only move to visible non-rival tiles.");
throw new InvalidOperationException("Archers can only move to visible tiles.");
}
var now = DateTime.UtcNow;
@@ -187,6 +187,8 @@ public class UnitTrainingService
.Set(x => x.Status, "Idle")
.Set(x => x.UpdatedAtUtc, now));
await ClaimTargetIfEmptyAsync(username, request.ToQ, request.ToR, now);
return await _units.Find(x =>
x.Username == username &&
x.UnitType == ArcherUnitType &&
@@ -226,15 +228,62 @@ public class UnitTrainingService
private async Task<bool> CanMoveToAsync(string username, int q, int r)
{
var ownedLocations = await _locations.Find(x => x.OwnerUsername == username).ToListAsync();
if (!ownedLocations.Any(owned => HexDistance(owned.Q, owned.R, q, r) <= _visibilityDepth))
if (ownedLocations.Any(owned => HexDistance(owned.Q, owned.R, q, r) <= _visibilityDepth))
{
return false;
return true;
}
var playerUnits = await _units.Find(x => x.Username == username).ToListAsync();
return playerUnits.Any(unit => HexDistance(unit.Q, unit.R, q, r) <= 1);
}
private async Task ClaimTargetIfEmptyAsync(string username, int q, int r, DateTime now)
{
var hasOtherUnits = await _units.Find(x => x.Username != username && x.Q == q && x.R == r).AnyAsync();
var target = await _locations.Find(x => x.Q == q && x.R == r).FirstOrDefaultAsync();
return target is null ||
string.IsNullOrWhiteSpace(target.OwnerUsername) ||
string.Equals(target.OwnerUsername, username, StringComparison.OrdinalIgnoreCase);
var hasBuilding = target is not null && !string.IsNullOrWhiteSpace(target.BuildingType);
if (hasOtherUnits || hasBuilding)
{
return;
}
if (target is null)
{
var location = new Location
{
Q = q,
R = r,
Terrain = "Field",
Kind = "Claimed",
OwnerUsername = username,
Level = 1,
CreatedAtUtc = now,
UpdatedAtUtc = now
};
try
{
await _locations.InsertOneAsync(location);
}
catch (MongoWriteException)
{
}
return;
}
if (string.Equals(target.OwnerUsername, username, StringComparison.OrdinalIgnoreCase))
{
return;
}
await _locations.UpdateOneAsync(
x => x.Id == target.Id && (x.BuildingType == null || x.BuildingType == ""),
Builders<Location>.Update
.Set(x => x.OwnerUsername, username)
.Set(x => x.Kind, "Claimed")
.Set(x => x.UpdatedAtUtc, now));
}
private static int HexDistance(int q1, int r1, int q2, int r2)