diff --git a/Game/Dungeon/CraftingHandler.cs b/Game/Dungeon/CraftingHandler.cs new file mode 100644 index 0000000..d0c4d8b --- /dev/null +++ b/Game/Dungeon/CraftingHandler.cs @@ -0,0 +1,439 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Server.Data; +using Server.Data.Entities; +using Server.Networking; +using Server.Networking.Messages; +using System.Text.Json; + +namespace Server.Game.Dungeon; + +/// +/// Handles crafting operations including recipe discovery, crafting, and skill progression +/// +public class CraftingHandler +{ + private readonly ILogger _log; + private readonly IServiceScopeFactory _scopeFactory; + + // Cache recipes in memory for fast lookup + private Dictionary _recipes = new(); + private Dictionary _ingredientHashToRecipeId = new(); // For recipe discovery + private bool _recipesLoaded = false; + + public CraftingHandler(ILogger log, IServiceScopeFactory scopeFactory) + { + _log = log; + _scopeFactory = scopeFactory; + } + + public async Task InitializeAsync() + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var recipes = await db.DungeonCraftingRecipes + .Include(r => r.Ingredients) + .Where(r => r.IsEnabled) + .ToListAsync(); + + _recipes = recipes.ToDictionary(r => r.Id); + + // Build ingredient hash lookup for recipe discovery + foreach (var recipe in recipes) + { + var hash = GetIngredientHash(recipe.Ingredients.OrderBy(i => i.SlotOrder).ToList()); + _ingredientHashToRecipeId[hash] = recipe.Id; + } + + _recipesLoaded = true; + _log.LogInformation("CraftingHandler loaded {Count} recipes", recipes.Count); + } + + /// + /// Get crafting skill for a character, creating if it doesn't exist + /// + public async Task GetOrCreateCraftingSkillAsync( + GameDbContext db, ulong characterId, CraftingSkillType skillType) + { + var skill = await db.DungeonCharacterCraftingSkills + .FirstOrDefaultAsync(s => s.CharacterId == characterId && s.SkillType == skillType); + + if (skill == null) + { + skill = new DungeonCharacterCraftingSkill + { + CharacterId = characterId, + SkillType = skillType, + Level = 1, + Experience = 0 + }; + db.DungeonCharacterCraftingSkills.Add(skill); + await db.SaveChangesAsync(); + } + + return skill; + } + + /// + /// Get all crafting skills for a character + /// + public async Task> GetAllCraftingSkillsAsync( + GameDbContext db, ulong characterId) + { + var skills = await db.DungeonCharacterCraftingSkills + .Where(s => s.CharacterId == characterId) + .ToListAsync(); + + var result = new Dictionary(); + + // Ensure all skill types exist + foreach (CraftingSkillType skillType in Enum.GetValues(typeof(CraftingSkillType))) + { + var skill = skills.FirstOrDefault(s => s.SkillType == skillType); + if (skill == null) + { + skill = new DungeonCharacterCraftingSkill + { + CharacterId = characterId, + SkillType = skillType, + Level = 1, + Experience = 0 + }; + db.DungeonCharacterCraftingSkills.Add(skill); + } + result[skillType] = skill; + } + + await db.SaveChangesAsync(); + return result; + } + + /// + /// Get known recipes for a character + /// + public async Task> GetKnownRecipesAsync(GameDbContext db, ulong characterId) + { + // Get explicitly known recipes + var knownRecipeIds = await db.DungeonCharacterKnownRecipes + .Where(kr => kr.CharacterId == characterId) + .Select(kr => kr.RecipeId) + .ToListAsync(); + + // Also include base recipes that everyone knows + var baseRecipeIds = _recipes.Values + .Where(r => r.IsBaseRecipe) + .Select(r => r.Id); + + var allKnownIds = knownRecipeIds.Union(baseRecipeIds).ToHashSet(); + + return _recipes.Values.Where(r => allKnownIds.Contains(r.Id)).ToList(); + } + + /// + /// Try to discover a recipe by combining ingredients + /// Returns the recipe if discovered, null otherwise + /// + public async Task<(DungeonCraftingRecipe? Recipe, bool AlreadyKnown)> TryDiscoverRecipeAsync( + GameDbContext db, ulong characterId, List<(int ItemDefinitionId, int Quantity)> ingredients) + { + // Build hash from ingredients + var sortedIngredients = ingredients.OrderBy(i => i.ItemDefinitionId).ThenBy(i => i.Quantity).ToList(); + var hash = GetIngredientHashFromInput(sortedIngredients); + + if (!_ingredientHashToRecipeId.TryGetValue(hash, out var recipeId)) + { + return (null, false); + } + + var recipe = _recipes[recipeId]; + + // Check if already known + var alreadyKnown = await db.DungeonCharacterKnownRecipes + .AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); + + if (alreadyKnown) + { + return (recipe, true); + } + + // Learn the recipe + db.DungeonCharacterKnownRecipes.Add(new DungeonCharacterKnownRecipe + { + CharacterId = characterId, + RecipeId = recipeId, + DiscoveredAt = DateTime.UtcNow + }); + await db.SaveChangesAsync(); + + _log.LogInformation("Character {CharId} discovered recipe: {Recipe}", characterId, recipe.Name); + + return (recipe, false); + } + + /// + /// Craft an item from a known recipe + /// + public async Task CraftItemAsync( + GameDbContext db, + ulong characterId, + int recipeId, + DungeonCharacter character) + { + if (!_recipes.TryGetValue(recipeId, out var recipe)) + { + return new CraftingResult { Success = false, ErrorMessage = "Recipe not found" }; + } + + // Verify character knows the recipe + var isBaseRecipe = recipe.IsBaseRecipe; + var knowsRecipe = isBaseRecipe || await db.DungeonCharacterKnownRecipes + .AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); + + if (!knowsRecipe) + { + return new CraftingResult { Success = false, ErrorMessage = "You don't know this recipe" }; + } + + // Get crafting skill + var skill = await GetOrCreateCraftingSkillAsync(db, characterId, recipe.SkillType); + + // Check level requirement + if (skill.Level < recipe.RequiredLevel) + { + return new CraftingResult + { + Success = false, + ErrorMessage = $"Requires {recipe.SkillType} level {recipe.RequiredLevel}" + }; + } + + // Verify ingredients + var inventory = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && !i.IsEquipped) + .ToListAsync(); + + var ingredientsToConsume = new List<(DungeonCharacterItem Item, int ConsumeCount)>(); + + foreach (var ingredient in recipe.Ingredients) + { + var availableItems = inventory + .Where(i => i.ItemDefinitionId == ingredient.ItemDefinitionId) + .ToList(); + + int totalAvailable = availableItems.Sum(i => i.Quantity); + if (totalAvailable < ingredient.Quantity) + { + var itemDef = await db.DungeonItemDefinitions.FindAsync(ingredient.ItemDefinitionId); + return new CraftingResult + { + Success = false, + ErrorMessage = $"Need {ingredient.Quantity} {itemDef?.Name ?? "items"} (have {totalAvailable})" + }; + } + + // Mark items to consume + int remaining = ingredient.Quantity; + foreach (var item in availableItems) + { + if (remaining <= 0) break; + int toConsume = Math.Min(remaining, item.Quantity); + ingredientsToConsume.Add((item, toConsume)); + remaining -= toConsume; + } + } + + // Consume ingredients + foreach (var (item, consumeCount) in ingredientsToConsume) + { + item.Quantity -= consumeCount; + if (item.Quantity <= 0) + { + db.DungeonCharacterItems.Remove(item); + } + } + + // Create output item + var outputItemDef = await db.DungeonItemDefinitions.FindAsync(recipe.OutputItemDefinitionId); + if (outputItemDef == null) + { + return new CraftingResult { Success = false, ErrorMessage = "Invalid recipe output" }; + } + + DungeonCraftedItem? craftedItem = null; + var rollResults = new List<(string Stat, int Value)>(); + + // Handle stat rolling for equipment + if (recipe.HasStatRolls && recipe.PossibleStats.Count > 0) + { + var rng = new Random(); + craftedItem = new DungeonCraftedItem + { + BaseItemDefinitionId = recipe.OutputItemDefinitionId, + CrafterId = characterId, + CrafterName = character.Name, + RecipeId = recipeId, + CraftedAt = DateTime.UtcNow, + CraftingLevelAtCreation = skill.Level + }; + + // Roll stats + int rollCount = skill.StatRollCount; + int minRoll = skill.MinStatRoll; + int maxRoll = skill.MaxStatRoll; + int totalRolled = 0; + int maxPossibleTotal = 0; + + for (int i = 0; i < rollCount; i++) + { + var stat = recipe.PossibleStats[rng.Next(recipe.PossibleStats.Count)]; + int value = rng.Next(minRoll, maxRoll + 1); + totalRolled += value; + maxPossibleTotal += maxRoll; + + ApplyStatRoll(craftedItem, stat, value); + rollResults.Add((stat, value)); + } + + // Calculate quality rating (0-100 based on how good the rolls were) + craftedItem.QualityRating = maxPossibleTotal > 0 + ? (int)(100f * totalRolled / maxPossibleTotal) + : 50; + + craftedItem.RollHistoryJson = JsonSerializer.Serialize(rollResults.Select(r => new { stat = r.Stat, value = r.Value })); + + db.DungeonCraftedItems.Add(craftedItem); + } + + // Find empty inventory slot + var usedSlots = inventory.Where(i => i.CharacterId == characterId && !i.IsEquipped).Select(i => i.SlotIndex).ToHashSet(); + int emptySlot = -1; + for (int i = 0; i < 30; i++) + { + if (!usedSlots.Contains(i)) + { + emptySlot = i; + break; + } + } + + if (emptySlot == -1) + { + return new CraftingResult { Success = false, ErrorMessage = "Inventory full" }; + } + + // Create the inventory item + var newItem = new DungeonCharacterItem + { + CharacterId = characterId, + ItemDefinitionId = recipe.OutputItemDefinitionId, + Quantity = recipe.OutputQuantity, + SlotIndex = emptySlot, + IsEquipped = false, + AcquiredAt = DateTime.UtcNow + }; + db.DungeonCharacterItems.Add(newItem); + await db.SaveChangesAsync(); + + // Link crafted item if applicable + if (craftedItem != null) + { + db.DungeonCharacterItemCraftedLinks.Add(new DungeonCharacterItemCraftedLink + { + CharacterItemId = newItem.Id, + CraftedItemId = craftedItem.Id + }); + } + + // Award XP + int xpGained = DungeonCharacterCraftingSkill.GetCraftingXp(recipe.Tier, skill.Level); + skill.Experience += xpGained; + skill.TotalItemsCrafted++; + + // Check for level up + bool leveledUp = false; + while (skill.Level < 100 && skill.Experience >= skill.ExperienceForNextLevel) + { + skill.Experience -= skill.ExperienceForNextLevel; + skill.Level++; + leveledUp = true; + } + + // Update known recipe craft count + var knownRecipe = await db.DungeonCharacterKnownRecipes + .FirstOrDefaultAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); + if (knownRecipe != null) + { + knownRecipe.TimesCrafted++; + } + + await db.SaveChangesAsync(); + + _log.LogInformation("Character {CharId} crafted {Item} (quality {Quality}, +{Xp} XP)", + characterId, outputItemDef.Name, craftedItem?.QualityRating ?? 0, xpGained); + + return new CraftingResult + { + Success = true, + OutputItem = outputItemDef, + CraftedItem = craftedItem, + RollResults = rollResults, + XpGained = xpGained, + NewSkillLevel = skill.Level, + LeveledUp = leveledUp, + SlotIndex = emptySlot + }; + } + + private void ApplyStatRoll(DungeonCraftedItem item, string stat, int value) + { + switch (stat) + { + case "BonusStrength": item.RolledBonusStrength += value; break; + case "BonusIntelligence": item.RolledBonusIntelligence += value; break; + case "BonusWisdom": item.RolledBonusWisdom += value; break; + case "BonusEndurance": item.RolledBonusEndurance += value; break; + case "BonusDexterity": item.RolledBonusDexterity += value; break; + case "BonusHealth": item.RolledBonusHealth += value; break; + case "BonusMana": item.RolledBonusMana += value; break; + case "Armor": item.RolledBonusArmor += value; break; + case "MagicResist": item.RolledBonusMagicResist += value; break; + case "MinDamage": item.RolledBonusMinDamage += value; break; + case "MaxDamage": item.RolledBonusMaxDamage += value; break; + case "HealAmount": item.RolledBonusHealAmount += value; break; + case "ManaRestore": item.RolledBonusManaRestore += value; break; + } + } + + private string GetIngredientHash(List ingredients) + { + var parts = ingredients + .OrderBy(i => i.ItemDefinitionId) + .ThenBy(i => i.Quantity) + .Select(i => $"{i.ItemDefinitionId}:{i.Quantity}"); + return string.Join("|", parts); + } + + private string GetIngredientHashFromInput(List<(int ItemDefinitionId, int Quantity)> ingredients) + { + var parts = ingredients + .OrderBy(i => i.ItemDefinitionId) + .ThenBy(i => i.Quantity) + .Select(i => $"{i.ItemDefinitionId}:{i.Quantity}"); + return string.Join("|", parts); + } +} + +public class CraftingResult +{ + public bool Success { get; set; } + public string? ErrorMessage { get; set; } + public DungeonItemDefinition? OutputItem { get; set; } + public DungeonCraftedItem? CraftedItem { get; set; } + public List<(string Stat, int Value)> RollResults { get; set; } = new(); + public int XpGained { get; set; } + public int NewSkillLevel { get; set; } + public bool LeveledUp { get; set; } + public int SlotIndex { get; set; } +} diff --git a/Networking/Messages/DungeonOpCodes.cs b/Networking/Messages/DungeonOpCodes.cs index 00d9767..dafbec8 100644 --- a/Networking/Messages/DungeonOpCodes.cs +++ b/Networking/Messages/DungeonOpCodes.cs @@ -71,4 +71,15 @@ public static class DungeonOpCodes // Player Death (280-289) public const int PLAYER_DEATH_LOOT_LOST = 280; // Notifies victim what they lost + + // Crafting (330-349) + public const int CRAFTING_SKILLS_REQUEST = 330; + public const int CRAFTING_SKILLS_STATE = 331; + public const int CRAFTING_RECIPES_REQUEST = 332; + public const int CRAFTING_RECIPES_STATE = 333; + public const int CRAFTING_ATTEMPT = 334; // Try to craft or discover + public const int CRAFTING_RESULT = 335; // Result of craft attempt + public const int CRAFTING_SKILL_LEVELUP = 336; // Skill level increased + public const int RECIPE_DISCOVERED = 337; // New recipe learned + public const int RECIPE_SCROLL_USE = 338; // Use a recipe scroll } diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index 4a21cf9..46117e4 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -35,6 +35,16 @@ public sealed class GameDbContext : DbContext public DbSet DeathChestItems => Set(); public DbSet DungeonInstances => Set(); public DbSet ClientAssets => Set(); + + // Crafting system + public DbSet DungeonCharacterCraftingSkills => Set(); + public DbSet DungeonCraftingRecipes => Set(); + public DbSet DungeonCraftingRecipeIngredients => Set(); + public DbSet DungeonCharacterKnownRecipes => Set(); + public DbSet DungeonRecipeScrolls => Set(); + public DbSet DungeonCraftedItems => Set(); + public DbSet DungeonCharacterItemCraftedLinks => Set(); + protected override void OnModelCreating(ModelBuilder b) { b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly); diff --git a/data/entities/CraftedItem.cs b/data/entities/CraftedItem.cs new file mode 100644 index 0000000..a66e28c --- /dev/null +++ b/data/entities/CraftedItem.cs @@ -0,0 +1,146 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// A crafted item with randomly rolled stats +/// This extends the base item definition with crafted bonuses +/// +[Table("dungeon_crafted_items")] +public class DungeonCraftedItem +{ + [Key] + public ulong Id { get; set; } + + /// + /// The base item definition this was crafted from + /// + [Required] + public int BaseItemDefinitionId { get; set; } + + /// + /// The character who crafted this item + /// + public ulong? CrafterId { get; set; } + + /// + /// Name of the crafter (stored separately in case character is deleted) + /// + [MaxLength(32)] + public string? CrafterName { get; set; } + + /// + /// The recipe used to craft this + /// + public int? RecipeId { get; set; } + + /// + /// When this item was crafted + /// + public DateTime CraftedAt { get; set; } = DateTime.UtcNow; + + /// + /// Crafting skill level when this was made + /// + public int CraftingLevelAtCreation { get; set; } = 1; + + // Rolled stat bonuses (added to base item stats) + public int RolledBonusStrength { get; set; } = 0; + public int RolledBonusIntelligence { get; set; } = 0; + public int RolledBonusWisdom { get; set; } = 0; + public int RolledBonusEndurance { get; set; } = 0; + public int RolledBonusDexterity { get; set; } = 0; + public int RolledBonusHealth { get; set; } = 0; + public int RolledBonusMana { get; set; } = 0; + public int RolledBonusArmor { get; set; } = 0; + public int RolledBonusMagicResist { get; set; } = 0; + public int RolledBonusMinDamage { get; set; } = 0; + public int RolledBonusMaxDamage { get; set; } = 0; + public int RolledBonusHealAmount { get; set; } = 0; + public int RolledBonusManaRestore { get; set; } = 0; + + /// + /// Quality rating based on how good the rolls were (0-100) + /// + public int QualityRating { get; set; } = 50; + + /// + /// Custom name given by crafter (optional) + /// + [MaxLength(64)] + public string? CustomName { get; set; } + + /// + /// JSON storing the individual rolls for display + /// e.g., [{"stat": "BonusStrength", "value": 5}, {"stat": "MinDamage", "value": 3}] + /// + [MaxLength(1024)] + public string? RollHistoryJson { get; set; } + + // Navigation + public virtual DungeonItemDefinition? BaseItemDefinition { get; set; } + public virtual DungeonCharacter? Crafter { get; set; } + public virtual DungeonCraftingRecipe? Recipe { get; set; } + + /// + /// Get the display name (custom name or base item name with quality prefix) + /// + [NotMapped] + public string DisplayName + { + get + { + if (!string.IsNullOrEmpty(CustomName)) return CustomName; + + string prefix = QualityRating switch + { + >= 95 => "Masterwork ", + >= 85 => "Exceptional ", + >= 70 => "Fine ", + >= 50 => "", + >= 30 => "Crude ", + _ => "Poor " + }; + + return prefix + (BaseItemDefinition?.Name ?? "Item"); + } + } + + /// + /// Get total bonus value for sorting/comparison + /// + [NotMapped] + public int TotalBonusValue => + RolledBonusStrength + RolledBonusIntelligence + RolledBonusWisdom + + RolledBonusEndurance + RolledBonusDexterity + RolledBonusHealth + + RolledBonusMana + RolledBonusArmor + RolledBonusMagicResist + + RolledBonusMinDamage + RolledBonusMaxDamage + RolledBonusHealAmount + + RolledBonusManaRestore; +} + +/// +/// Maps a DungeonCharacterItem to a DungeonCraftedItem if it was crafted +/// +[Table("dungeon_character_item_crafted_link")] +public class DungeonCharacterItemCraftedLink +{ + [Key] + public ulong Id { get; set; } + + /// + /// The character's inventory item + /// + [Required] + public ulong CharacterItemId { get; set; } + + /// + /// The crafted item data + /// + [Required] + public ulong CraftedItemId { get; set; } + + // Navigation + public virtual DungeonCharacterItem? CharacterItem { get; set; } + public virtual DungeonCraftedItem? CraftedItem { get; set; } +} diff --git a/data/entities/CraftingRecipes.cs b/data/entities/CraftingRecipes.cs new file mode 100644 index 0000000..f2d08c6 --- /dev/null +++ b/data/entities/CraftingRecipes.cs @@ -0,0 +1,183 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// A crafting recipe that can produce an item +/// Recipes are discovered through trial-and-error +/// +[Table("dungeon_crafting_recipes")] +public class DungeonCraftingRecipe +{ + [Key] + public int Id { get; set; } + + /// + /// Name of the recipe (e.g., "Iron Sword", "Health Potion") + /// + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + /// + /// Description of the recipe + /// + [MaxLength(256)] + public string Description { get; set; } = ""; + + /// + /// Which crafting skill is used + /// + public CraftingSkillType SkillType { get; set; } + + /// + /// Minimum crafting level required to craft this recipe + /// + public int RequiredLevel { get; set; } = 1; + + /// + /// Item definition ID that this recipe produces + /// + public int OutputItemDefinitionId { get; set; } + + /// + /// How many items are produced per craft + /// + public int OutputQuantity { get; set; } = 1; + + /// + /// Tier of the recipe (affects XP gain and stat rolls) + /// + public int Tier { get; set; } = 1; + + /// + /// Base XP awarded for crafting (modified by level difference) + /// + public int BaseXp { get; set; } = 25; + + /// + /// Whether this is a "base" recipe everyone knows, or must be discovered + /// + public bool IsBaseRecipe { get; set; } = false; + + /// + /// If true, the output item gets random stat rolls + /// If false, it's a fixed item (like potions) + /// + public bool HasStatRolls { get; set; } = false; + + /// + /// JSON array of possible stats that can roll on this item + /// e.g., ["BonusStrength", "BonusDexterity", "MinDamage", "MaxDamage"] + /// + [MaxLength(1024)] + public string? PossibleStatsJson { get; set; } + + public bool IsEnabled { get; set; } = true; + + // Navigation + public virtual DungeonItemDefinition? OutputItem { get; set; } + public virtual ICollection Ingredients { get; set; } = new List(); + + // Helper to get possible stats + [NotMapped] + public List PossibleStats + { + get + { + if (string.IsNullOrEmpty(PossibleStatsJson)) return new List(); + try { return System.Text.Json.JsonSerializer.Deserialize>(PossibleStatsJson) ?? new List(); } + catch { return new List(); } + } + } +} + +/// +/// An ingredient required for a recipe +/// +[Table("dungeon_crafting_recipe_ingredients")] +public class DungeonCraftingRecipeIngredient +{ + [Key] + public int Id { get; set; } + + [Required] + public int RecipeId { get; set; } + + /// + /// Item definition ID of the required ingredient + /// + [Required] + public int ItemDefinitionId { get; set; } + + /// + /// How many of this item are needed + /// + public int Quantity { get; set; } = 1; + + /// + /// Order for recipe matching (ingredients must match in order for discovery) + /// + public int SlotOrder { get; set; } = 0; + + // Navigation + public virtual DungeonCraftingRecipe? Recipe { get; set; } + public virtual DungeonItemDefinition? ItemDefinition { get; set; } +} + +/// +/// Tracks which recipes a character has discovered +/// +[Table("dungeon_character_known_recipes")] +public class DungeonCharacterKnownRecipe +{ + [Key] + public ulong Id { get; set; } + + [Required] + public ulong CharacterId { get; set; } + + [Required] + public int RecipeId { get; set; } + + /// + /// When the recipe was discovered + /// + public DateTime DiscoveredAt { get; set; } = DateTime.UtcNow; + + /// + /// How many times this recipe has been crafted + /// + public int TimesCrafted { get; set; } = 0; + + // Navigation + public virtual DungeonCharacter? Character { get; set; } + public virtual DungeonCraftingRecipe? Recipe { get; set; } +} + +/// +/// A recipe scroll item that can teach a recipe when used +/// +[Table("dungeon_recipe_scrolls")] +public class DungeonRecipeScroll +{ + [Key] + public int Id { get; set; } + + /// + /// The item definition ID of this scroll + /// + [Required] + public int ItemDefinitionId { get; set; } + + /// + /// The recipe this scroll teaches + /// + [Required] + public int RecipeId { get; set; } + + // Navigation + public virtual DungeonItemDefinition? ItemDefinition { get; set; } + public virtual DungeonCraftingRecipe? Recipe { get; set; } +} diff --git a/data/entities/CraftingSkills.cs b/data/entities/CraftingSkills.cs new file mode 100644 index 0000000..17e38ae --- /dev/null +++ b/data/entities/CraftingSkills.cs @@ -0,0 +1,149 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// Types of crafting skills +/// +public enum CraftingSkillType +{ + Smithing = 0, // Weapons, Armor (metal-based) + Fletching = 1, // Bows, Arrows, Crossbows + Jewelry = 2, // Rings, Amulets, Accessories + Alchemy = 3, // Potions, Resource Transmutation + Academic = 4 // Scrolls, Spellbooks, Enchantments +} + +/// +/// A character's progress in a crafting skill +/// +[Table("dungeon_character_crafting_skills")] +public class DungeonCharacterCraftingSkill +{ + [Key] + public ulong Id { get; set; } + + [Required] + public ulong CharacterId { get; set; } + + [Required] + public CraftingSkillType SkillType { get; set; } + + /// + /// Current level in this crafting skill (1-100) + /// + public int Level { get; set; } = 1; + + /// + /// XP progress toward next level + /// + public long Experience { get; set; } = 0; + + /// + /// Total items crafted with this skill + /// + public int TotalItemsCrafted { get; set; } = 0; + + // Navigation + public virtual DungeonCharacter? Character { get; set; } + + // Helper methods + [NotMapped] + public long ExperienceForNextLevel => GetXpForLevel(Level + 1); + + [NotMapped] + public float ProgressToNextLevel => Level >= 100 ? 1f : (float)Experience / ExperienceForNextLevel; + + /// + /// Number of stat rolls when crafting (increases with level) + /// Level 1-19: 1 roll + /// Level 20-39: 2 rolls + /// Level 40-59: 3 rolls + /// Level 60-79: 4 rolls + /// Level 80-99: 5 rolls + /// Level 100: 6 rolls + /// + [NotMapped] + public int StatRollCount => Math.Min(6, 1 + (Level / 20)); + + /// + /// Minimum stat roll value (increases with level) + /// + [NotMapped] + public int MinStatRoll => 1 + (Level / 10); + + /// + /// Maximum stat roll value (increases with level) + /// + [NotMapped] + public int MaxStatRoll => 5 + (Level / 5); + + /// + /// XP required to reach a specific level + /// Uses exponential curve: base * level^2 + /// + public static long GetXpForLevel(int level) + { + if (level <= 1) return 0; + return (long)(100 * Math.Pow(level, 2.2)); + } + + /// + /// XP gained from crafting an item of a certain tier + /// + public static int GetCraftingXp(int itemTier, int craftingLevel) + { + // Base XP from tier + int baseXp = itemTier * 25; + + // Bonus for crafting items near your level + int levelDiff = Math.Abs(itemTier * 10 - craftingLevel); + float multiplier = Math.Max(0.1f, 1.0f - (levelDiff * 0.05f)); + + return (int)(baseXp * multiplier); + } +} + +/// +/// Static helper for crafting skill calculations +/// +public static class CraftingSkillHelper +{ + /// + /// Get which crafting skill is used for a given item type + /// + public static CraftingSkillType? GetSkillForItemType(ItemType itemType, string itemName = "") + { + switch (itemType) + { + case ItemType.Weapon: + // Check if it's a bow/crossbow (fletching) or metal weapon (smithing) + if (itemName.Contains("bow", StringComparison.OrdinalIgnoreCase) || + itemName.Contains("arrow", StringComparison.OrdinalIgnoreCase) || + itemName.Contains("crossbow", StringComparison.OrdinalIgnoreCase)) + return CraftingSkillType.Fletching; + return CraftingSkillType.Smithing; + + case ItemType.Armor: + return CraftingSkillType.Smithing; + + case ItemType.Accessory: + return CraftingSkillType.Jewelry; + + case ItemType.Consumable: + // Check if it's a scroll (academic) or potion (alchemy) + if (itemName.Contains("scroll", StringComparison.OrdinalIgnoreCase) || + itemName.Contains("tome", StringComparison.OrdinalIgnoreCase) || + itemName.Contains("book", StringComparison.OrdinalIgnoreCase)) + return CraftingSkillType.Academic; + return CraftingSkillType.Alchemy; + + case ItemType.Material: + return null; // Materials aren't crafted directly + + default: + return null; + } + } +} diff --git a/data/entities/DungeonCharacter.cs b/data/entities/DungeonCharacter.cs index 7ef8f51..8bd123b 100644 --- a/data/entities/DungeonCharacter.cs +++ b/data/entities/DungeonCharacter.cs @@ -75,4 +75,6 @@ public class DungeonCharacter public virtual ICollection Inventory { get; set; } = new List(); public virtual ICollection Stash { get; set; } = new List(); public virtual ICollection LearnedSpells { get; set; } = new List(); + public virtual ICollection CraftingSkills { get; set; } = new List(); + public virtual ICollection KnownRecipes { get; set; } = new List(); }