Resistance System

This commit is contained in:
dingo
2025-12-26 10:40:09 -05:00
parent 2d847c91dd
commit fd056692df
16 changed files with 2862 additions and 8 deletions
+35
View File
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
using Server.Services.Auth;
namespace Server.Api;
@@ -342,3 +343,37 @@ public class BootstrapRequest
public string Username { get; set; } = "";
public string BootstrapKey { get; set; } = "";
}
/// <summary>
/// Get all resistance types for dropdowns
/// </summary>
[ApiController]
[Route("api/admin/resistances")]
public class ResistanceTypesController : ControllerBase
{
private readonly GameDbContext _db;
public ResistanceTypesController(GameDbContext db)
{
_db = db;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var types = await _db.DamageResistanceTypes
.Where(t => t.IsEnabled)
.OrderBy(t => t.SortOrder)
.Select(t => new { t.Key, t.DisplayName, t.Color })
.ToListAsync();
return Ok(types);
}
[HttpGet("check/{key}")]
public async Task<IActionResult> CheckExists(string key)
{
var exists = await _db.DamageResistanceTypes
.AnyAsync(t => t.Key.ToLower() == key.ToLower() && t.IsEnabled);
return Ok(new { exists });
}
}
+191
View File
@@ -0,0 +1,191 @@
using DataServer.Data.Entities;
using DataServer.Data.Enums;
namespace Server.Game.Dungeon;
/// <summary>
/// Handles damage calculations with stats, gear, and resistances
/// </summary>
public static class CombatCalculator
{
/// <summary>
/// Calculate damage dealt from player to mob
/// </summary>
public static DamageResult CalculatePlayerToMobDamage(
PlayerInstance player,
MobInstance mob,
DamageType damageType,
int baseDamage,
Dictionary<string, float>? playerGearResistances = null)
{
// 1. Base damage modified by player stats
float damage = baseDamage;
// Physical damage scales with STR
if (damageType == DamageType.Physical)
{
damage *= 1 + (player.Strength * 0.05f); // 5% per STR
}
// Magical damage scales with INT
else
{
damage *= 1 + (player.Intelligence * 0.05f); // 5% per INT
}
// 2. Apply mob's armor/magic resist reduction
float mitigation = 0f;
if (damageType == DamageType.Physical)
{
// Armor formula: damage reduction = armor / (armor + 100)
mitigation = mob.Stats.Armor / (float)(mob.Stats.Armor + 100);
}
else
{
// Magic resist formula
mitigation = mob.Stats.MagicResist / (float)(mob.Stats.MagicResist + 100);
}
damage *= (1 - mitigation);
// 3. Apply mob's elemental resistances
string resistKey = damageType.ToString().ToLower();
if (mob.Stats.Resistances.TryGetValue(resistKey, out float mobResist))
{
// Positive = resistance (reduces damage), Negative = weakness (increases damage)
// 0.5 = 50% resistance, -0.25 = 25% weakness, 1.0 = immune
if (mobResist >= 1.0f)
{
// Immune
return new DamageResult
{
FinalDamage = 0,
WasResisted = true,
WasImmune = true,
DamageType = damageType
};
}
damage *= (1 - mobResist);
}
// 4. Ensure minimum damage of 1
int finalDamage = Math.Max(1, (int)damage);
return new DamageResult
{
FinalDamage = finalDamage,
WasResisted = mobResist > 0,
WasWeakness = mobResist < 0,
DamageType = damageType
};
}
/// <summary>
/// Calculate damage dealt from mob to player
/// </summary>
public static DamageResult CalculateMobToPlayerDamage(
MobInstance mob,
PlayerInstance player,
DamageType damageType,
int baseDamage,
Dictionary<string, float> playerTotalResistances)
{
float damage = baseDamage;
// 1. Apply player's armor/magic resist reduction
float mitigation = 0f;
if (damageType == DamageType.Physical)
{
// Player armor from gear + endurance bonus
int playerArmor = player.Armor;
mitigation = playerArmor / (float)(playerArmor + 100);
}
else
{
int playerMagicResist = player.MagicResist;
mitigation = playerMagicResist / (float)(playerMagicResist + 100);
}
damage *= (1 - mitigation);
// 2. Apply player's elemental resistances (from gear + innate)
string resistKey = damageType.ToString().ToLower();
float playerResist = 0f;
if (playerTotalResistances.TryGetValue(resistKey, out float resist))
{
playerResist = resist;
}
// Cap resistance at 75% to prevent immunity stacking
playerResist = Math.Min(playerResist, 0.75f);
if (playerResist != 0)
{
damage *= (1 - playerResist);
}
// 3. Endurance provides flat damage reduction
float enduranceReduction = player.Endurance * 0.5f; // 0.5 flat reduction per END
damage = Math.Max(1, damage - enduranceReduction);
int finalDamage = Math.Max(1, (int)damage);
return new DamageResult
{
FinalDamage = finalDamage,
WasResisted = playerResist > 0,
WasWeakness = playerResist < 0,
DamageType = damageType
};
}
/// <summary>
/// Calculate total resistances for a player from innate + gear
/// </summary>
public static Dictionary<string, float> CalculatePlayerTotalResistances(
Dictionary<string, float> innateResistances,
List<DungeonItemDefinition> equippedItems)
{
var total = new Dictionary<string, float>(innateResistances);
foreach (var item in equippedItems)
{
foreach (var resist in item.Resistances)
{
if (total.ContainsKey(resist.Key))
total[resist.Key] += resist.Value;
else
total[resist.Key] = resist.Value;
}
}
return total;
}
/// <summary>
/// Calculate player weapon damage range
/// </summary>
public static (int min, int max, DamageType type) GetPlayerWeaponDamage(
PlayerInstance player,
DungeonItemDefinition? weapon)
{
if (weapon == null)
{
// Unarmed: base damage + STR
int unarmedMin = 1 + (int)(player.Strength * 0.5f);
int unarmedMax = 3 + (int)(player.Strength * 0.5f);
return (unarmedMin, unarmedMax, DamageType.Physical);
}
return (weapon.MinDamage, weapon.MaxDamage, weapon.DamageType);
}
}
public class DamageResult
{
public int FinalDamage { get; set; }
public bool WasResisted { get; set; }
public bool WasWeakness { get; set; }
public bool WasImmune { get; set; }
public bool WasCritical { get; set; }
public DamageType DamageType { get; set; }
}
+41 -7
View File
@@ -273,8 +273,18 @@ public class DungeonSimulation
private void MobAttackPlayer(MobInstance mob, PlayerInstance player)
{
int damage = mob.Stats.PhysicalDamage + mob.Stats.MagicDamage;
player.Health -= damage;
// Determine damage type (physical if mob has no magic damage)
var damageType = mob.Stats.MagicDamage > mob.Stats.PhysicalDamage
? DataServer.Data.Enums.DamageType.Fire // Use fire for magic mobs (could be configured per mob)
: DataServer.Data.Enums.DamageType.Physical;
int baseDamage = mob.Stats.PhysicalDamage + mob.Stats.MagicDamage;
// Calculate damage with resistances
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, player, damageType, baseDamage, player.Resistances);
player.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
@@ -284,7 +294,9 @@ public class DungeonSimulation
SourceId = mob.Id,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = damage
Damage = result.FinalDamage,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
});
if (player.Health <= 0)
@@ -347,10 +359,30 @@ public class DungeonSimulation
float dist = Distance(player.X, player.Y, mob.X, mob.Y);
if (dist > 60) return; // Out of range
// Calculate damage
int damage = (int)(10 * (1 + player.Strength * 0.05f));
// Base damage from stats (would be enhanced by equipped weapon in full implementation)
int baseDamage = 10 + (int)(player.Strength * 0.5f);
var damageType = DataServer.Data.Enums.DamageType.Physical;
mob.Health -= damage;
// Calculate damage with mob resistances
var result = CombatCalculator.CalculatePlayerToMobDamage(
player, mob, damageType, baseDamage);
if (result.WasImmune)
{
// Mob is immune, still add event for client feedback
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = 0,
WasImmune = true
});
return;
}
mob.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
@@ -360,7 +392,9 @@ public class DungeonSimulation
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = damage
Damage = result.FinalDamage,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
});
if (mob.Health <= 0)
+12
View File
@@ -22,6 +22,18 @@ public class PlayerInstance
public float AttackSpeed { get; set; } = 1f;
public int Strength { get; set; }
public int Intelligence { get; set; }
public int Wisdom { get; set; }
public int Endurance { get; set; }
public int Dexterity { get; set; }
// Defensive stats (from gear)
public int Armor { get; set; }
public int MagicResist { get; set; }
/// <summary>
/// Combined resistances from innate + gear
/// </summary>
public Dictionary<string, float> Resistances { get; set; } = new();
public bool IsAlive { get; set; } = true;
public bool IsInCombat { get; set; }
+15
View File
@@ -17,6 +17,21 @@ public class DamageEvent
public int TargetId { get; set; }
public int Damage { get; set; }
public DamageType DamageType { get; set; }
/// <summary>
/// True if damage was reduced by resistance
/// </summary>
public bool WasResisted { get; set; }
/// <summary>
/// True if damage was increased by weakness
/// </summary>
public bool WasWeakness { get; set; }
/// <summary>
/// True if target was immune (0 damage)
/// </summary>
public bool WasImmune { get; set; }
}
public class DeathEvent
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,75 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class ResistanceSystemtweaks : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ResistancesJson",
table: "dungeon_item_definitions",
type: "varchar(1024)",
maxLength: 1024,
nullable: false,
defaultValue: "")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "ResistancesJson",
table: "dungeon_characters",
type: "varchar(1024)",
maxLength: 1024,
nullable: false,
defaultValue: "")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "damage_resistance_types",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Key = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
DisplayName = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Description = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Color = table.Column<string>(type: "varchar(16)", maxLength: 16, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
IconPath = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_damage_resistance_types", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "damage_resistance_types");
migrationBuilder.DropColumn(
name: "ResistancesJson",
table: "dungeon_item_definitions");
migrationBuilder.DropColumn(
name: "ResistancesJson",
table: "dungeon_characters");
}
}
}
+56
View File
@@ -133,6 +133,52 @@ namespace SystemRevivalServer.Migrations
b.ToTable("client_assets");
});
modelBuilder.Entity("DataServer.Data.Entities.DamageResistanceType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Color")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("varchar(16)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<string>("IconPath")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("damage_resistance_types");
});
modelBuilder.Entity("DataServer.Data.Entities.DeathChest", b =>
{
b.Property<ulong>("Id")
@@ -321,6 +367,11 @@ namespace SystemRevivalServer.Migrations
b.Property<int>("PlayersKilled")
.HasColumnType("int");
b.Property<string>("ResistancesJson")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("varchar(1024)");
b.Property<int>("Strength")
.HasColumnType("int");
@@ -744,6 +795,11 @@ namespace SystemRevivalServer.Migrations
b.Property<int>("RequiredWisdom")
.HasColumnType("int");
b.Property<string>("ResistancesJson")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("varchar(1024)");
b.Property<int>("SpriteId")
.HasColumnType("int");
@@ -174,7 +174,8 @@
(DungeonEquipmentSlot.Legs, "Legs"),
(DungeonEquipmentSlot.Boots, "Boots"),
(DungeonEquipmentSlot.Gloves, "Gloves"),
(DungeonEquipmentSlot.Accessory1, "Accessory")
(DungeonEquipmentSlot.Accessory1, "Accessory 1"),
(DungeonEquipmentSlot.Accessory2, "Accessory 2")
})
{
var item = Model.EquippedItems.FirstOrDefault(i => i.EquipSlot == slot.Item1);
@@ -0,0 +1,188 @@
@page "/admin/resistances"
@model Resistances.IndexModel
@{
ViewData["Title"] = "Damage Resistance Types";
}
<div class="space-y-6 max-w-4xl">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold text-white">Damage Resistance Types</h1>
<p class="text-gray-400 mt-1">Define resistance types for mobs, players, and items</p>
</div>
</div>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="p-4 rounded-lg @(Model.IsError ? "bg-red-900/50 border border-red-700 text-red-300" : "bg-green-900/50 border border-green-700 text-green-300")">
@Model.Message
</div>
}
<!-- Add New Type -->
<form method="post" asp-page-handler="Create" class="card p-6">
@Html.AntiForgeryToken()
<h2 class="text-lg font-semibold text-white mb-4">Add New Resistance Type</h2>
<div class="grid grid-cols-1 md:grid-cols-6 gap-4 mb-4">
<div class="md:col-span-2">
<label class="label">Key (lowercase, no spaces)</label>
<input type="text" name="key" class="input" required pattern="[a-z0-9_]+" maxlength="32" placeholder="e.g., bleed"
oninput="this.value = this.value.toLowerCase().replace(/[^a-z0-9_]/g, '')" />
</div>
<div class="md:col-span-2">
<label class="label">Display Name</label>
<input type="text" name="displayName" class="input" required maxlength="64" placeholder="e.g., Bleeding" />
</div>
<div>
<label class="label">Color</label>
<div class="flex gap-2">
<input type="color" id="newColor" value="#888888" class="w-10 h-10 rounded border border-gray-700 bg-gray-800 cursor-pointer"
oninput="document.getElementById('newColorText').value=this.value" />
<input type="text" id="newColorText" name="color" value="#888888" class="input flex-1" maxlength="16" />
</div>
</div>
<div>
<label class="label">Order</label>
<input type="number" name="sortOrder" value="@(Model.Types.Count * 10)" class="input" min="0" />
</div>
</div>
<div class="mb-4">
<label class="label">Description (optional)</label>
<input type="text" name="description" class="input" maxlength="256" placeholder="What this damage type represents..." />
</div>
<button type="submit" class="btn btn-primary">Add Resistance Type</button>
</form>
<!-- Existing Types -->
<div class="card overflow-hidden">
<table class="w-full">
<thead class="bg-gray-800">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">Color</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">Key</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">Display Name</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">Description</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">Order</th>
<th class="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700">
@foreach (var type in Model.Types)
{
<tr class="hover:bg-gray-800/50">
<td class="px-4 py-3">
<div class="w-6 h-6 rounded" style="background-color: @type.Color"></div>
</td>
<td class="px-4 py-3">
<code class="text-indigo-400 bg-gray-800 px-2 py-0.5 rounded text-sm">@type.Key</code>
</td>
<td class="px-4 py-3 text-white">@type.DisplayName</td>
<td class="px-4 py-3 text-gray-400 text-sm">@(string.IsNullOrEmpty(type.Description) ? "-" : type.Description)</td>
<td class="px-4 py-3 text-gray-400">@type.SortOrder</td>
<td class="px-4 py-3 text-right">
<button type="button" onclick="editType(@type.Id, '@type.Key', '@type.DisplayName', '@type.Description', '@type.Color', @type.SortOrder)"
class="btn btn-secondary text-xs px-2 py-1">Edit</button>
<form method="post" asp-page-handler="Delete" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@type.Id" />
<button type="submit" class="btn bg-red-700 hover:bg-red-600 text-white text-xs px-2 py-1"
onclick="return confirm('Delete @type.DisplayName? This may break existing resistances using this type.')">Delete</button>
</form>
</td>
</tr>
}
@if (!Model.Types.Any())
{
<tr>
<td colspan="6" class="px-4 py-8 text-center text-gray-400">
No resistance types defined. Add the base types above.
</td>
</tr>
}
</tbody>
</table>
</div>
<!-- Seed Base Types -->
@if (!Model.Types.Any())
{
<form method="post" asp-page-handler="SeedDefaults" class="card p-6 text-center">
@Html.AntiForgeryToken()
<p class="text-gray-400 mb-4">Want to start with the default damage types?</p>
<button type="submit" class="btn btn-primary">Seed Default Resistance Types</button>
</form>
}
</div>
<!-- Edit Modal -->
<div id="editModal" class="fixed inset-0 bg-black/70 hidden items-center justify-center z-50">
<div class="bg-gray-800 rounded-xl p-6 max-w-md w-full mx-4 border border-gray-700">
<h3 class="text-lg font-semibold text-white mb-4">Edit Resistance Type</h3>
<form method="post" asp-page-handler="Update">
@Html.AntiForgeryToken()
<input type="hidden" name="id" id="editId" />
<div class="space-y-4">
<div>
<label class="label">Key (read-only)</label>
<input type="text" id="editKey" class="input bg-gray-900" readonly />
</div>
<div>
<label class="label">Display Name</label>
<input type="text" name="displayName" id="editDisplayName" class="input" required maxlength="64" />
</div>
<div>
<label class="label">Description</label>
<input type="text" name="description" id="editDescription" class="input" maxlength="256" />
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="label">Color</label>
<div class="flex gap-2">
<input type="color" id="editColorPicker" class="w-10 h-10 rounded border border-gray-700 bg-gray-800 cursor-pointer"
oninput="document.getElementById('editColor').value=this.value" />
<input type="text" name="color" id="editColor" class="input flex-1" maxlength="16" />
</div>
</div>
<div>
<label class="label">Sort Order</label>
<input type="number" name="sortOrder" id="editSortOrder" class="input" min="0" />
</div>
</div>
</div>
<div class="flex justify-end gap-3 pt-4 mt-4 border-t border-gray-700">
<button type="button" onclick="closeEditModal()" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
@section Scripts {
<script>
function editType(id, key, displayName, description, color, sortOrder) {
document.getElementById('editId').value = id;
document.getElementById('editKey').value = key;
document.getElementById('editDisplayName').value = displayName;
document.getElementById('editDescription').value = description || '';
document.getElementById('editColor').value = color;
document.getElementById('editColorPicker').value = color;
document.getElementById('editSortOrder').value = sortOrder;
document.getElementById('editModal').classList.remove('hidden');
document.getElementById('editModal').classList.add('flex');
}
function closeEditModal() {
document.getElementById('editModal').classList.add('hidden');
document.getElementById('editModal').classList.remove('flex');
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeEditModal(); });
</script>
}
@@ -0,0 +1,133 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
namespace Server.Services.Admin.Pages.Resistances;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<DamageResistanceType> Types { get; set; } = new();
[TempData]
public string? Message { get; set; }
[TempData]
public bool IsError { get; set; }
public async Task OnGetAsync()
{
Types = await _db.DamageResistanceTypes
.Where(t => t.IsEnabled)
.OrderBy(t => t.SortOrder)
.ThenBy(t => t.DisplayName)
.ToListAsync();
}
public async Task<IActionResult> OnPostCreateAsync(string key, string displayName, string? description, string color, int sortOrder)
{
key = key?.Trim().ToLower().Replace(" ", "_") ?? "";
if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(displayName))
{
Message = "Key and Display Name are required.";
IsError = true;
return RedirectToPage();
}
// Check for duplicate key (case insensitive)
var existing = await _db.DamageResistanceTypes
.FirstOrDefaultAsync(t => t.Key.ToLower() == key.ToLower());
if (existing != null)
{
Message = $"A resistance type with key '{key}' already exists.";
IsError = true;
return RedirectToPage();
}
var type = new DamageResistanceType
{
Key = key,
DisplayName = displayName,
Description = description ?? "",
Color = color ?? "#888888",
SortOrder = sortOrder,
IsEnabled = true
};
_db.DamageResistanceTypes.Add(type);
await _db.SaveChangesAsync();
Message = $"Resistance type '{displayName}' created.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostUpdateAsync(int id, string displayName, string? description, string color, int sortOrder)
{
var type = await _db.DamageResistanceTypes.FindAsync(id);
if (type == null)
{
Message = "Resistance type not found.";
IsError = true;
return RedirectToPage();
}
type.DisplayName = displayName;
type.Description = description ?? "";
type.Color = color ?? "#888888";
type.SortOrder = sortOrder;
await _db.SaveChangesAsync();
Message = $"Resistance type '{displayName}' updated.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var type = await _db.DamageResistanceTypes.FindAsync(id);
if (type != null)
{
// Soft delete by disabling
type.IsEnabled = false;
await _db.SaveChangesAsync();
Message = $"Resistance type '{type.DisplayName}' deleted.";
}
return RedirectToPage();
}
public async Task<IActionResult> OnPostSeedDefaultsAsync()
{
var defaults = new[]
{
new DamageResistanceType { Key = "physical", DisplayName = "Physical", Color = "#a0a0a0", SortOrder = 0 },
new DamageResistanceType { Key = "fire", DisplayName = "Fire", Color = "#ff4400", SortOrder = 10 },
new DamageResistanceType { Key = "ice", DisplayName = "Ice", Color = "#00aaff", SortOrder = 20 },
new DamageResistanceType { Key = "lightning", DisplayName = "Lightning", Color = "#ffff00", SortOrder = 30 },
new DamageResistanceType { Key = "poison", DisplayName = "Poison", Color = "#00ff44", SortOrder = 40 },
new DamageResistanceType { Key = "holy", DisplayName = "Holy", Color = "#ffffaa", SortOrder = 50 },
new DamageResistanceType { Key = "dark", DisplayName = "Dark", Color = "#8800aa", SortOrder = 60 },
new DamageResistanceType { Key = "wind", DisplayName = "Wind", Color = "#88ffaa", SortOrder = 70 },
};
foreach (var def in defaults)
{
var existing = await _db.DamageResistanceTypes
.FirstOrDefaultAsync(t => t.Key == def.Key);
if (existing == null)
{
_db.DamageResistanceTypes.Add(def);
}
}
await _db.SaveChangesAsync();
Message = "Default resistance types seeded.";
return RedirectToPage();
}
}
@@ -112,6 +112,13 @@
Loot Tables
</a>
<a href="/admin/resistances" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/Resistances") == true ? "active" : "")">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
</svg>
Resistances
</a>
<div class="pt-4">
<p class="px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">Management</p>
</div>
+3
View File
@@ -41,6 +41,9 @@ public sealed class GameDbContext : DbContext
public DbSet<DungeonCraftedItem> DungeonCraftedItems => Set<DungeonCraftedItem>();
public DbSet<DungeonCharacterItemCraftedLink> DungeonCharacterItemCraftedLinks => Set<DungeonCharacterItemCraftedLink>();
// Damage system
public DbSet<DamageResistanceType> DamageResistanceTypes => Set<DamageResistanceType>();
protected override void OnModelCreating(ModelBuilder b)
{
b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly);
+60
View File
@@ -0,0 +1,60 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataServer.Data.Entities;
/// <summary>
/// Defines a damage resistance type that can be applied to mobs, players, and items.
/// This allows for dynamic resistance types beyond the base DamageType enum.
/// </summary>
[Table("damage_resistance_types")]
public class DamageResistanceType
{
[Key]
public int Id { get; set; }
/// <summary>
/// Internal key name (lowercase, no spaces) - e.g., "fire", "ice", "bleed"
/// Used in JSON resistance blocks
/// </summary>
[Required]
[MaxLength(32)]
public string Key { get; set; } = "";
/// <summary>
/// Display name for UI - e.g., "Fire", "Ice", "Bleeding"
/// </summary>
[Required]
[MaxLength(64)]
public string DisplayName { get; set; } = "";
/// <summary>
/// Description of what this resistance does
/// </summary>
[MaxLength(256)]
public string Description { get; set; } = "";
/// <summary>
/// Hex color for UI display (e.g., "#ff4400" for fire)
/// </summary>
[MaxLength(16)]
public string Color { get; set; } = "#888888";
/// <summary>
/// Icon path on CDN (optional)
/// </summary>
[MaxLength(256)]
public string? IconPath { get; set; }
/// <summary>
/// Sort order for display in dropdowns
/// </summary>
public int SortOrder { get; set; } = 0;
/// <summary>
/// Whether this resistance type is available for use
/// </summary>
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}
+23
View File
@@ -1,5 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json;
namespace DataServer.Data.Entities;
@@ -70,6 +71,28 @@ public class DungeonCharacter
// Soft delete
public bool IsDeleted { get; set; } = false;
/// <summary>
/// JSON block for innate resistances/weaknesses (from skills, buffs, etc.)
/// Example: {"fire": 0.1, "poison": -0.2}
/// Stacks with gear resistances
/// </summary>
[MaxLength(1024)]
public string ResistancesJson { get; set; } = "{}";
/// <summary>
/// Helper to get/set resistances dictionary
/// </summary>
[NotMapped]
public Dictionary<string, float> Resistances
{
get
{
try { return JsonSerializer.Deserialize<Dictionary<string, float>>(ResistancesJson) ?? new(); }
catch { return new(); }
}
set { ResistancesJson = JsonSerializer.Serialize(value); }
}
// Navigation
public virtual Account? Account { get; set; }
public virtual ICollection<DungeonCharacterItem> Inventory { get; set; } = new List<DungeonCharacterItem>();
+23
View File
@@ -1,5 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json;
using DataServer.Data.Enums;
namespace DataServer.Data.Entities;
@@ -80,5 +81,27 @@ public class DungeonItemDefinition
// Legacy field - kept for backwards compatibility
public int SpriteId { get; set; } = 0;
/// <summary>
/// JSON block for resistance bonuses when equipped
/// Example: {"fire": 0.15, "ice": 0.10}
/// Values are percentage (0.15 = 15% resistance)
/// </summary>
[MaxLength(1024)]
public string ResistancesJson { get; set; } = "{}";
/// <summary>
/// Helper to get/set resistances dictionary
/// </summary>
[NotMapped]
public Dictionary<string, float> Resistances
{
get
{
try { return JsonSerializer.Deserialize<Dictionary<string, float>>(ResistancesJson) ?? new(); }
catch { return new(); }
}
set { ResistancesJson = JsonSerializer.Serialize(value); }
}
public bool IsEnabled { get; set; } = true;
}