Adding interactable object spawning

This commit is contained in:
2026-03-19 16:35:07 -05:00
parent 932f7be66b
commit 1aefd5ba88
12 changed files with 768 additions and 68 deletions
@@ -76,11 +76,42 @@ public class LocationStore
}
}
},
{ "biomeKey", new BsonDocument { { "bsonType", new BsonArray { "string", "null" } } } },
{
"locationObject", new BsonDocument
{
{ "bsonType", new BsonArray { "object", "null" } },
{
"properties", new BsonDocument
{
{ "id", new BsonDocument { { "bsonType", "string" } } },
{ "objectType", new BsonDocument { { "bsonType", "string" } } },
{ "objectKey", new BsonDocument { { "bsonType", "string" } } },
{ "name", new BsonDocument { { "bsonType", "string" } } },
{
"state", new BsonDocument
{
{ "bsonType", new BsonArray { "object", "null" } },
{
"properties", new BsonDocument
{
{ "itemKey", new BsonDocument { { "bsonType", "string" } } },
{ "remainingQuantity", new BsonDocument { { "bsonType", "int" }, { "minimum", 0 } } },
{ "gatherQuantity", new BsonDocument { { "bsonType", "int" }, { "minimum", 1 } } }
}
}
}
}
}
}
}
},
{ "locationObjectResolved", new BsonDocument { { "bsonType", new BsonArray { "bool", "null" } } } },
{ "createdUtc", new BsonDocument { { "bsonType", "date" } } }
}
}
}
}
}
}
};
var collections = db.ListCollectionNames().ToList();
@@ -125,54 +156,79 @@ public class LocationStore
return result.ModifiedCount > 0;
}
public sealed record GatherResult(GatherStatus Status, string ResourceKey = "", int QuantityGranted = 0, int RemainingQuantity = 0);
public sealed record InteractResult(
InteractStatus Status,
string ObjectId = "",
string ObjectType = "",
string ItemKey = "",
int QuantityGranted = 0,
int RemainingQuantity = 0,
bool Consumed = false,
LocationObject? PreviousObject = null);
public async Task<GatherResult> GatherResourceAsync(string locationId, string characterId, string resourceKey, string userId, bool allowAnyOwner)
public async Task<InteractResult> InteractWithObjectAsync(string locationId, string characterId, string objectId, string userId, bool allowAnyOwner)
{
var normalizedKey = resourceKey.Trim().ToLowerInvariant();
var location = await _col.Find(l => l.Id == locationId).FirstOrDefaultAsync();
if (location is null)
return new GatherResult(GatherStatus.LocationNotFound);
return new InteractResult(InteractStatus.LocationNotFound);
location = await EnsureLocationMetadataAsync(location);
var character = await _characters.Find(c => c.Id == characterId).FirstOrDefaultAsync();
if (character is null)
return new GatherResult(GatherStatus.CharacterNotFound);
return new InteractResult(InteractStatus.CharacterNotFound);
if (!allowAnyOwner && character.OwnerUserId != userId)
return new GatherResult(GatherStatus.Forbidden);
return new InteractResult(InteractStatus.Forbidden);
if (character.Coord.X != location.Coord.X || character.Coord.Y != location.Coord.Y)
return new GatherResult(GatherStatus.Invalid);
return new InteractResult(InteractStatus.Invalid);
var resource = location.Resources.FirstOrDefault(r => NormalizeItemKey(r.ItemKey) == normalizedKey);
if (resource is null)
return new GatherResult(GatherStatus.ResourceNotFound);
if (resource.RemainingQuantity <= 0)
return new GatherResult(GatherStatus.ResourceDepleted);
var locationObject = location.LocationObject;
if (locationObject is null)
return new InteractResult(InteractStatus.ObjectNotFound);
if (!string.Equals(locationObject.Id, objectId, StringComparison.Ordinal))
return new InteractResult(InteractStatus.ObjectNotFound);
if (!string.Equals(locationObject.ObjectType, "gatherable", StringComparison.OrdinalIgnoreCase))
return new InteractResult(InteractStatus.UnsupportedObjectType);
if (locationObject.State.RemainingQuantity <= 0)
return new InteractResult(InteractStatus.ObjectConsumed);
var quantityGranted = Math.Min(resource.GatherQuantity, resource.RemainingQuantity);
var filter = Builders<Location>.Filter.And(
var quantityGranted = Math.Min(locationObject.State.GatherQuantity, locationObject.State.RemainingQuantity);
var remainingQuantity = locationObject.State.RemainingQuantity - quantityGranted;
var objectFilter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Eq(l => l.Id, locationId),
Builders<Location>.Filter.ElemMatch(l => l.Resources, r => r.ItemKey == resource.ItemKey && r.RemainingQuantity >= quantityGranted)
Builders<Location>.Filter.Eq("locationObject.id", locationObject.Id),
Builders<Location>.Filter.Eq("locationObject.state.remainingQuantity", locationObject.State.RemainingQuantity)
);
var update = Builders<Location>.Update.Inc("resources.$.remainingQuantity", -quantityGranted);
var result = await _col.UpdateOneAsync(filter, update);
if (result.ModifiedCount == 0)
return new GatherResult(GatherStatus.ResourceDepleted);
return new GatherResult(
GatherStatus.Ok,
resource.ItemKey,
UpdateDefinition<Location> update;
if (remainingQuantity <= 0)
{
update = Builders<Location>.Update.Unset("locationObject");
}
else
{
update = Builders<Location>.Update.Set("locationObject.state.remainingQuantity", remainingQuantity);
}
var result = await _col.UpdateOneAsync(objectFilter, update);
if (result.ModifiedCount == 0)
return new InteractResult(InteractStatus.ObjectConsumed);
return new InteractResult(
InteractStatus.Ok,
locationObject.Id,
locationObject.ObjectType,
locationObject.State.ItemKey,
quantityGranted,
resource.RemainingQuantity - quantityGranted);
Math.Max(0, remainingQuantity),
remainingQuantity <= 0,
CloneLocationObject(locationObject));
}
public async Task RestoreGatheredResourceAsync(string locationId, string resourceKey, int quantity)
public async Task RestoreObjectInteractionAsync(string locationId, LocationObject previousObject)
{
var normalizedKey = NormalizeItemKey(resourceKey);
var filter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Eq(l => l.Id, locationId),
Builders<Location>.Filter.ElemMatch(l => l.Resources, r => r.ItemKey == normalizedKey)
);
var update = Builders<Location>.Update.Inc("resources.$.remainingQuantity", quantity);
var filter = Builders<Location>.Filter.Eq(l => l.Id, locationId);
var update = Builders<Location>.Update.Set(l => l.LocationObject, previousObject);
await _col.UpdateOneAsync(filter, update);
}
@@ -220,18 +276,16 @@ public class LocationStore
Builders<Location>.Filter.Eq(l => l.Coord.Y, 0)
);
var existing = _col.Find(filter).FirstOrDefault();
if (existing is not null)
return;
if (existing is not null)
return;
var origin = new Location
{
Name = "Origin",
Coord = new Coord { X = 0, Y = 0 },
Resources =
[
new LocationResource { ItemKey = "wood", RemainingQuantity = 100, GatherQuantity = 3 },
new LocationResource { ItemKey = "grass", RemainingQuantity = 500, GatherQuantity = 10 }
],
BiomeKey = DetermineBiomeKey(0, 0),
LocationObject = CreateLocationObjectForBiome(DetermineBiomeKey(0, 0), 0, 0),
LocationObjectResolved = true,
CreatedUtc = DateTime.UtcNow
};
@@ -247,6 +301,150 @@ public class LocationStore
private static string NormalizeItemKey(string itemKey) => itemKey.Trim().ToLowerInvariant();
private async Task<Location> EnsureLocationMetadataAsync(Location location)
{
if (!string.IsNullOrWhiteSpace(location.BiomeKey) && location.LocationObjectResolved)
return location;
var biomeKey = location.BiomeKey;
if (string.IsNullOrWhiteSpace(biomeKey))
biomeKey = DetermineBiomeKey(location.Coord.X, location.Coord.Y);
var migratedObject = TryMigrateLegacyResources(location) ?? CreateLocationObjectForBiome(biomeKey, location.Coord.X, location.Coord.Y);
var filter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Eq(l => l.Id, location.Id)
);
var update = Builders<Location>.Update
.Set(l => l.BiomeKey, biomeKey)
.Set(l => l.LocationObjectResolved, true)
.Set(l => l.LocationObject, migratedObject);
await _col.UpdateOneAsync(filter, update);
location.BiomeKey = biomeKey;
location.LocationObject = migratedObject;
location.LocationObjectResolved = true;
return location;
}
private static LocationObject? TryMigrateLegacyResources(Location location)
{
var legacyResource = location.Resources.FirstOrDefault(r => r.RemainingQuantity > 0);
if (legacyResource is null)
return null;
return CreateGatherableObject(
legacyResource.ItemKey,
legacyResource.RemainingQuantity,
legacyResource.GatherQuantity);
}
private static string DetermineBiomeKey(int x, int y)
{
if (x == 0 && y == 0)
return "plains";
var regionX = FloorDiv(x, 4);
var regionY = FloorDiv(y, 4);
var roll = Math.Abs(HashCode.Combine(regionX, regionY, 7919)) % 100;
if (roll < 35)
return "plains";
if (roll < 60)
return "forest";
if (roll < 80)
return "rocky";
if (roll < 92)
return "wetlands";
return "desert";
}
private static LocationObject? CreateLocationObjectForBiome(string biomeKey, int x, int y)
{
var roll = Math.Abs(HashCode.Combine(x, y, 1543)) % 100;
return biomeKey switch
{
"forest" => roll switch
{
< 35 => null,
< 80 => CreateGatherableObject("wood", 60, 3),
< 95 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("stone", 40, 2)
},
"rocky" => roll switch
{
< 60 => null,
< 90 => CreateGatherableObject("stone", 40, 2),
_ => CreateGatherableObject("wood", 60, 3)
},
"wetlands" => roll switch
{
< 40 => null,
< 90 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("wood", 60, 3)
},
"desert" => roll switch
{
< 70 => null,
< 95 => CreateGatherableObject("stone", 40, 2),
_ => CreateGatherableObject("wood", 60, 3)
},
_ => roll switch
{
< 50 => null,
< 85 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("wood", 60, 3)
}
};
}
private static LocationObject CreateGatherableObject(string itemKey, int remainingQuantity, int gatherQuantity)
{
var normalizedItemKey = NormalizeItemKey(itemKey);
return new LocationObject
{
Id = Guid.NewGuid().ToString("N"),
ObjectType = "gatherable",
ObjectKey = $"{normalizedItemKey}_node",
Name = HumanizeItemKey(normalizedItemKey),
State = new LocationObjectState
{
ItemKey = normalizedItemKey,
RemainingQuantity = remainingQuantity,
GatherQuantity = gatherQuantity
}
};
}
private static string HumanizeItemKey(string itemKey)
{
return string.Join(" ", itemKey.Split('_', StringSplitOptions.RemoveEmptyEntries)
.Select(part => char.ToUpperInvariant(part[0]) + part[1..]));
}
private static int FloorDiv(int value, int divisor)
{
var quotient = value / divisor;
var remainder = value % divisor;
if (remainder != 0 && ((remainder < 0) != (divisor < 0)))
quotient -= 1;
return quotient;
}
private static LocationObject CloneLocationObject(LocationObject source)
{
return new LocationObject
{
Id = source.Id,
ObjectType = source.ObjectType,
ObjectKey = source.ObjectKey,
Name = source.Name,
State = new LocationObjectState
{
ItemKey = source.State.ItemKey,
RemainingQuantity = source.State.RemainingQuantity,
GatherQuantity = source.State.GatherQuantity
}
};
}
[MongoDB.Bson.Serialization.Attributes.BsonIgnoreExtraElements]
private class CharacterDocument
{
@@ -260,13 +458,14 @@ public class LocationStore
}
}
public enum GatherStatus
public enum InteractStatus
{
Ok,
LocationNotFound,
CharacterNotFound,
Forbidden,
Invalid,
ResourceNotFound,
ResourceDepleted
ObjectNotFound,
UnsupportedObjectType,
ObjectConsumed
}