Dungeon Browser
This commit is contained in:
@@ -76,7 +76,11 @@ public sealed class DungeonHandler : IClientMessageHandler
|
||||
DungeonOpCodes.LOOT_CHEST_OPEN,
|
||||
DungeonOpCodes.LOOT_CHEST_TAKE_ITEM,
|
||||
DungeonOpCodes.LOOT_CHEST_TAKE_ALL,
|
||||
DungeonOpCodes.LOOT_CHEST_CLOSE
|
||||
DungeonOpCodes.LOOT_CHEST_CLOSE,
|
||||
// Dungeon browser
|
||||
DungeonOpCodes.DUNGEON_LIST_REQUEST,
|
||||
DungeonOpCodes.DUNGEON_CREATE,
|
||||
DungeonOpCodes.DUNGEON_JOIN
|
||||
};
|
||||
|
||||
public async Task InitializeAsync()
|
||||
@@ -213,6 +217,17 @@ public sealed class DungeonHandler : IClientMessageHandler
|
||||
case DungeonOpCodes.LOOT_CHEST_CLOSE:
|
||||
await HandleLootChestClose(connection, session, payload, ct);
|
||||
break;
|
||||
|
||||
// Dungeon browser
|
||||
case DungeonOpCodes.DUNGEON_LIST_REQUEST:
|
||||
await HandleDungeonListRequest(connection, session, ct);
|
||||
break;
|
||||
case DungeonOpCodes.DUNGEON_CREATE:
|
||||
await HandleDungeonCreate(connection, session, payload, ct);
|
||||
break;
|
||||
case DungeonOpCodes.DUNGEON_JOIN:
|
||||
await HandleDungeonJoin(connection, session, payload, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -683,6 +698,16 @@ public sealed class DungeonHandler : IClientMessageHandler
|
||||
{
|
||||
// Fire and forget loot generation (async in sync context)
|
||||
_ = ProcessMobDeathLootAsync(instance, death);
|
||||
|
||||
// Check if this was a boss kill
|
||||
if (instance.Simulation.Mobs.TryGetValue(death.EntityId, out var killedMob))
|
||||
{
|
||||
if (killedMob.Type == MobType.Boss)
|
||||
{
|
||||
instance.BossKilled = true;
|
||||
_log.LogInformation("Boss killed in dungeon {Id}! Dungeon is now cleared.", dungeonId);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (death.EntityType == EntityType.Player)
|
||||
{
|
||||
@@ -727,10 +752,30 @@ public sealed class DungeonHandler : IClientMessageHandler
|
||||
_ = SendDungeonStateAsync(session, result);
|
||||
}
|
||||
|
||||
// Cleanup empty dungeons
|
||||
if (playersInDungeon.Count == 0 && (DateTime.UtcNow - instance.CreatedAt).TotalMinutes > 5)
|
||||
// Update last activity if players present
|
||||
if (playersInDungeon.Count > 0)
|
||||
{
|
||||
_dungeons.TryRemove(dungeonId, out _);
|
||||
instance.LastPlayerActivity = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
// Handle empty dungeon logic
|
||||
if (playersInDungeon.Count == 0)
|
||||
{
|
||||
var emptyTime = DateTime.UtcNow - instance.LastPlayerActivity;
|
||||
|
||||
// If boss not killed and empty for 10+ minutes, persist to database
|
||||
if (!instance.BossKilled && !instance.IsPersisted && emptyTime.TotalMinutes >= 10)
|
||||
{
|
||||
_ = PersistDungeonAsync(instance, CancellationToken.None);
|
||||
_dungeons.TryRemove(dungeonId, out _);
|
||||
_log.LogInformation("Dungeon {Id} persisted after 10 minutes empty", dungeonId);
|
||||
}
|
||||
// If boss killed and empty for 5+ minutes, just remove (cleared)
|
||||
else if (instance.BossKilled && emptyTime.TotalMinutes >= 5)
|
||||
{
|
||||
_dungeons.TryRemove(dungeonId, out _);
|
||||
_log.LogInformation("Cleared dungeon {Id} removed after 5 minutes empty", dungeonId);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -1537,6 +1582,433 @@ public sealed class DungeonHandler : IClientMessageHandler
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dungeon Browser Handlers
|
||||
|
||||
/// <summary>
|
||||
/// Handle request for list of available dungeons
|
||||
/// </summary>
|
||||
private async Task HandleDungeonListRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
||||
{
|
||||
var playerLevel = session.Character.Level;
|
||||
var (bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
|
||||
|
||||
// Get active dungeons in player's bracket
|
||||
var availableDungeons = _dungeons.Values
|
||||
.Where(d => d.IsLevelInBracket(playerLevel) &&
|
||||
d.Simulation.Phase == DungeonPhase.Active &&
|
||||
!d.BossKilled)
|
||||
.Select(d => new
|
||||
{
|
||||
id = d.Id.ToString(),
|
||||
tier = d.Tier,
|
||||
levelBracket = $"{d.LevelBracketMin}-{d.LevelBracketMax}",
|
||||
creatorName = d.CreatorName,
|
||||
creatorLevel = d.CreatorLevel,
|
||||
playerCount = d.Simulation.Players.Count,
|
||||
maxPlayers = 20,
|
||||
isJoinWindowOpen = d.IsJoinWindowOpen,
|
||||
createdAt = d.CreatedAt,
|
||||
secondsRemaining = d.IsJoinWindowOpen ? (int)(d.JoinWindowEnd - DateTime.UtcNow).TotalSeconds : 0
|
||||
})
|
||||
.OrderByDescending(d => d.isJoinWindowOpen)
|
||||
.ThenByDescending(d => d.createdAt)
|
||||
.ToList();
|
||||
|
||||
// Also load persisted dungeons from database
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var persistedDungeons = await db.Set<DungeonPersistence>()
|
||||
.Where(d => d.LevelBracketMin == bracketMin &&
|
||||
d.LevelBracketMax == bracketMax &&
|
||||
!d.IsCleared)
|
||||
.Select(d => new
|
||||
{
|
||||
id = d.Id.ToString(),
|
||||
tier = d.Tier,
|
||||
levelBracket = $"{d.LevelBracketMin}-{d.LevelBracketMax}",
|
||||
creatorName = d.CreatorName,
|
||||
creatorLevel = d.CreatorLevel,
|
||||
playerCount = 0,
|
||||
maxPlayers = 20,
|
||||
isJoinWindowOpen = false,
|
||||
isPersisted = true,
|
||||
createdAt = d.CreatedAt
|
||||
})
|
||||
.ToListAsync(ct);
|
||||
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_LIST_RESPONSE, new
|
||||
{
|
||||
playerLevel = playerLevel,
|
||||
bracket = new { min = bracketMin, max = bracketMax },
|
||||
activeDungeons = availableDungeons,
|
||||
persistedDungeons = persistedDungeons
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle creating a new dungeon
|
||||
/// </summary>
|
||||
private async Task HandleDungeonCreate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
if (session.State == PlayerState.InDungeon)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var request = _ser.Deserialize<DungeonCreateRequest>(payload);
|
||||
int tier = Math.Clamp(request.Tier, 1, 10);
|
||||
int playerLevel = session.Character.Level;
|
||||
var (bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
|
||||
|
||||
var dungeonId = Guid.NewGuid();
|
||||
int seed = Random.Shared.Next();
|
||||
|
||||
var layout = DungeonGenerator.Generate(seed, tier);
|
||||
var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin);
|
||||
|
||||
var instance = new DungeonInstance
|
||||
{
|
||||
Id = dungeonId,
|
||||
Tier = tier,
|
||||
Seed = seed,
|
||||
Simulation = simulation,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
LevelBracketMin = bracketMin,
|
||||
LevelBracketMax = bracketMax,
|
||||
CreatorLevel = playerLevel,
|
||||
CreatorCharacterId = session.CharacterId,
|
||||
CreatorName = session.Character.Name
|
||||
};
|
||||
|
||||
_dungeons[dungeonId] = instance;
|
||||
_log.LogInformation("Player {Name} (Level {Level}) created dungeon {Id} (tier {Tier}, bracket {Min}-{Max})",
|
||||
session.Character.Name, playerLevel, dungeonId, tier, bracketMin, bracketMax);
|
||||
|
||||
// Add player to dungeon
|
||||
await AddPlayerToDungeonAsync(connection, session, instance, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle joining an existing dungeon
|
||||
/// </summary>
|
||||
private async Task HandleDungeonJoin(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
if (session.State == PlayerState.InDungeon)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var request = _ser.Deserialize<DungeonJoinRequest>(payload);
|
||||
if (!Guid.TryParse(request.DungeonId, out var dungeonId))
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "invalid_dungeon_id" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
int playerLevel = session.Character.Level;
|
||||
|
||||
// Check if dungeon is in memory
|
||||
if (_dungeons.TryGetValue(dungeonId, out var instance))
|
||||
{
|
||||
// Validate level bracket
|
||||
if (!instance.IsLevelInBracket(playerLevel))
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
|
||||
{
|
||||
ok = false,
|
||||
error = "level_out_of_range",
|
||||
message = $"Your level ({playerLevel}) is outside the dungeon's level bracket ({instance.LevelBracketMin}-{instance.LevelBracketMax})"
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if full
|
||||
if (instance.Simulation.Players.Count >= 20)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_full" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if boss killed
|
||||
if (instance.BossKilled)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_cleared" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await AddPlayerToDungeonAsync(connection, session, instance, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to restore from persistence
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var persisted = await db.Set<DungeonPersistence>().FindAsync(new object[] { dungeonId }, ct);
|
||||
if (persisted == null)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_not_found" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (persisted.IsCleared)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_cleared" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate level bracket
|
||||
if (playerLevel < persisted.LevelBracketMin || playerLevel > persisted.LevelBracketMax)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
|
||||
{
|
||||
ok = false,
|
||||
error = "level_out_of_range",
|
||||
message = $"Your level ({playerLevel}) is outside the dungeon's level bracket ({persisted.LevelBracketMin}-{persisted.LevelBracketMax})"
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Restore dungeon from persistence
|
||||
instance = await RestoreDungeonFromPersistenceAsync(persisted, ct);
|
||||
if (instance == null)
|
||||
{
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "restore_failed" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
_dungeons[dungeonId] = instance;
|
||||
|
||||
// Remove from persistence table (it's active now)
|
||||
db.Set<DungeonPersistence>().Remove(persisted);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
await AddPlayerToDungeonAsync(connection, session, instance, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a player to a dungeon and send the result
|
||||
/// </summary>
|
||||
private async Task AddPlayerToDungeonAsync(IConnection connection, DungeonPlayerSession session, DungeonInstance instance, CancellationToken ct)
|
||||
{
|
||||
var layout = instance.Simulation.Layout;
|
||||
var spawnPos = layout.Rooms[0]; // Entrance room
|
||||
|
||||
var player = new PlayerInstance
|
||||
{
|
||||
CharacterId = session.CharacterId,
|
||||
CharacterName = session.Character.Name,
|
||||
X = spawnPos.CenterX * 32 + Random.Shared.Next(-20, 20),
|
||||
Y = spawnPos.CenterY * 32 + Random.Shared.Next(-20, 20),
|
||||
Health = session.Character.CurrentHealth,
|
||||
MaxHealth = DungeonCharacterStats.GetMaxHealth(session.Character),
|
||||
Mana = session.Character.CurrentMana,
|
||||
MaxMana = DungeonCharacterStats.GetMaxMana(session.Character),
|
||||
Stamina = DungeonCharacterStats.GetMaxStamina(session.Character),
|
||||
MaxStamina = DungeonCharacterStats.GetMaxStamina(session.Character),
|
||||
MoveSpeed = DungeonCharacterStats.GetMoveSpeed(session.Character),
|
||||
AttackSpeed = DungeonCharacterStats.GetAttackSpeed(session.Character),
|
||||
Strength = session.Character.Strength,
|
||||
Intelligence = session.Character.Intelligence
|
||||
};
|
||||
|
||||
instance.Simulation.Players[session.CharacterId] = player;
|
||||
instance.LastPlayerActivity = DateTime.UtcNow;
|
||||
|
||||
session.State = PlayerState.InDungeon;
|
||||
session.CurrentDungeonId = instance.Id;
|
||||
session.PlayerInstance = player;
|
||||
|
||||
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
|
||||
{
|
||||
ok = true,
|
||||
dungeonId = instance.Id.ToString(),
|
||||
tier = instance.Tier,
|
||||
seed = instance.Seed,
|
||||
levelBracket = new { min = instance.LevelBracketMin, max = instance.LevelBracketMax },
|
||||
width = layout.Width,
|
||||
height = layout.Height,
|
||||
tiles = layout.SerializeTiles(),
|
||||
spawn = new { x = player.X, y = player.Y },
|
||||
players = instance.Simulation.Players.Values.Select(p => new
|
||||
{
|
||||
id = p.CharacterId,
|
||||
name = p.CharacterName,
|
||||
x = p.X,
|
||||
y = p.Y
|
||||
}),
|
||||
mobs = instance.Simulation.Mobs.Values.Where(m => m.IsAlive).Select(m => new
|
||||
{
|
||||
id = m.Id,
|
||||
name = m.Name,
|
||||
x = m.X,
|
||||
y = m.Y,
|
||||
health = m.Health,
|
||||
maxHealth = m.MaxHealth,
|
||||
spriteSheet = m.SpriteSheet,
|
||||
spriteWidth = m.SpriteWidth,
|
||||
spriteHeight = m.SpriteHeight,
|
||||
tintColor = m.TintColor
|
||||
}),
|
||||
chests = instance.Simulation.Chests.Values.Select(c => new
|
||||
{
|
||||
id = c.Id,
|
||||
x = c.X,
|
||||
y = c.Y,
|
||||
type = c.Type.ToString().ToLower(),
|
||||
opened = c.IsOpened
|
||||
}),
|
||||
portals = instance.Simulation.Portals.Values.Where(p => p.IsActive).Select(p => new
|
||||
{
|
||||
id = p.Id,
|
||||
x = p.X,
|
||||
y = p.Y,
|
||||
type = p.Type.ToString().ToLower()
|
||||
})
|
||||
}, ct);
|
||||
|
||||
_log.LogInformation("Player {Name} (Level {Level}) joined dungeon {Id}",
|
||||
session.Character.Name, session.Character.Level, instance.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restore a dungeon from persistence
|
||||
/// </summary>
|
||||
private async Task<DungeonInstance?> RestoreDungeonFromPersistenceAsync(DungeonPersistence persisted, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var layout = DungeonGenerator.Generate(persisted.Seed, persisted.Tier);
|
||||
var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin);
|
||||
|
||||
// Restore mob state if available
|
||||
if (!string.IsNullOrEmpty(persisted.MobStateJson))
|
||||
{
|
||||
var mobStates = System.Text.Json.JsonSerializer.Deserialize<List<PersistedMobState>>(persisted.MobStateJson);
|
||||
if (mobStates != null)
|
||||
{
|
||||
foreach (var mobState in mobStates)
|
||||
{
|
||||
if (simulation.Mobs.TryGetValue(mobState.Id, out var mob))
|
||||
{
|
||||
mob.X = mobState.X;
|
||||
mob.Y = mobState.Y;
|
||||
mob.Health = mobState.Health;
|
||||
mob.IsAlive = mobState.IsAlive;
|
||||
if (!mob.IsAlive) mob.State = MobState.Dead;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore chest state if available
|
||||
if (!string.IsNullOrEmpty(persisted.ChestStateJson))
|
||||
{
|
||||
var chestStates = System.Text.Json.JsonSerializer.Deserialize<List<PersistedChestState>>(persisted.ChestStateJson);
|
||||
if (chestStates != null)
|
||||
{
|
||||
foreach (var chestState in chestStates)
|
||||
{
|
||||
if (simulation.Chests.TryGetValue(chestState.Id, out var chest))
|
||||
{
|
||||
chest.IsOpened = chestState.IsOpened;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var instance = new DungeonInstance
|
||||
{
|
||||
Id = persisted.Id,
|
||||
Tier = persisted.Tier,
|
||||
Seed = persisted.Seed,
|
||||
Simulation = simulation,
|
||||
CreatedAt = persisted.CreatedAt,
|
||||
LevelBracketMin = persisted.LevelBracketMin,
|
||||
LevelBracketMax = persisted.LevelBracketMax,
|
||||
CreatorLevel = persisted.CreatorLevel,
|
||||
CreatorCharacterId = persisted.CreatorCharacterId,
|
||||
CreatorName = persisted.CreatorName,
|
||||
BossKilled = persisted.BossKilled,
|
||||
IsPersisted = false,
|
||||
LastPlayerActivity = DateTime.UtcNow
|
||||
};
|
||||
|
||||
_log.LogInformation("Restored dungeon {Id} from persistence", persisted.Id);
|
||||
return instance;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Failed to restore dungeon {Id} from persistence", persisted.Id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persist a dungeon to SQL (called when empty for 10 minutes)
|
||||
/// </summary>
|
||||
private async Task PersistDungeonAsync(DungeonInstance instance, CancellationToken ct)
|
||||
{
|
||||
if (instance.IsPersisted || instance.BossKilled) return;
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
// Serialize mob state
|
||||
var mobStates = instance.Simulation.Mobs.Values.Select(m => new PersistedMobState
|
||||
{
|
||||
Id = m.Id,
|
||||
DefinitionId = m.DefinitionId,
|
||||
X = m.X,
|
||||
Y = m.Y,
|
||||
Health = m.Health,
|
||||
IsAlive = m.IsAlive
|
||||
}).ToList();
|
||||
|
||||
// Serialize chest state
|
||||
var chestStates = instance.Simulation.Chests.Values.Select(c => new PersistedChestState
|
||||
{
|
||||
Id = c.Id,
|
||||
IsOpened = c.IsOpened
|
||||
}).ToList();
|
||||
|
||||
var persisted = new DungeonPersistence
|
||||
{
|
||||
Id = instance.Id,
|
||||
Tier = instance.Tier,
|
||||
Seed = instance.Seed,
|
||||
LevelBracketMin = instance.LevelBracketMin,
|
||||
LevelBracketMax = instance.LevelBracketMax,
|
||||
CreatorCharacterId = instance.CreatorCharacterId,
|
||||
CreatorName = instance.CreatorName,
|
||||
CreatorLevel = instance.CreatorLevel,
|
||||
CreatedAt = instance.CreatedAt,
|
||||
LastActivity = instance.LastPlayerActivity,
|
||||
PersistedAt = DateTime.UtcNow,
|
||||
BossKilled = instance.BossKilled,
|
||||
MobStateJson = System.Text.Json.JsonSerializer.Serialize(mobStates),
|
||||
ChestStateJson = System.Text.Json.JsonSerializer.Serialize(chestStates)
|
||||
};
|
||||
|
||||
db.Set<DungeonPersistence>().Add(persisted);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
instance.IsPersisted = true;
|
||||
_log.LogInformation("Persisted dungeon {Id} to database", instance.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Failed to persist dungeon {Id}", instance.Id);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Sends loot popup to client showing what they received
|
||||
/// </summary>
|
||||
@@ -2299,3 +2771,13 @@ public class LootChestCloseRequest
|
||||
{
|
||||
public int ChestId { get; set; }
|
||||
}
|
||||
|
||||
public class DungeonCreateRequest
|
||||
{
|
||||
public int Tier { get; set; }
|
||||
}
|
||||
|
||||
public class DungeonJoinRequest
|
||||
{
|
||||
public string DungeonId { get; set; } = "";
|
||||
}
|
||||
|
||||
@@ -11,4 +11,45 @@ public class DungeonInstance
|
||||
public DungeonSimulation Simulation { get; set; } = null!;
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool ClearedHandled { get; set; } = false;
|
||||
|
||||
// Level bracket system
|
||||
public int LevelBracketMin { get; set; }
|
||||
public int LevelBracketMax { get; set; }
|
||||
public int CreatorLevel { get; set; }
|
||||
public ulong CreatorCharacterId { get; set; }
|
||||
public string CreatorName { get; set; } = "";
|
||||
|
||||
// Auto-join window (5 minutes)
|
||||
public DateTime JoinWindowEnd => CreatedAt.AddMinutes(5);
|
||||
public bool IsJoinWindowOpen => DateTime.UtcNow < JoinWindowEnd;
|
||||
|
||||
// Persistence
|
||||
public DateTime LastPlayerActivity { get; set; } = DateTime.UtcNow;
|
||||
public bool IsPersisted { get; set; } = false;
|
||||
public bool BossKilled { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Check if a player level is within the bracket range
|
||||
/// </summary>
|
||||
public bool IsLevelInBracket(int playerLevel)
|
||||
{
|
||||
return playerLevel >= LevelBracketMin && playerLevel <= LevelBracketMax;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculate level bracket from a player's level (brackets of 10: 1-10, 11-20, 21-30, etc.)
|
||||
/// </summary>
|
||||
public static (int min, int max) GetLevelBracket(int level)
|
||||
{
|
||||
// Bracket 1: 1-10, Bracket 2: 11-20, etc.
|
||||
int bracketIndex = (level - 1) / 10;
|
||||
int min = bracketIndex * 10 + 1;
|
||||
int max = min + 9;
|
||||
return (min, max);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the bracket number (1, 2, 3, etc.)
|
||||
/// </summary>
|
||||
public int BracketNumber => (LevelBracketMin - 1) / 10 + 1;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ public class DungeonSimulation
|
||||
{
|
||||
public DungeonLayout Layout { get; }
|
||||
public int Tier { get; }
|
||||
public int BracketMin { get; }
|
||||
|
||||
// Tick rate
|
||||
public const int TicksPerSecond = 20;
|
||||
@@ -38,10 +39,11 @@ public class DungeonSimulation
|
||||
private int _nextDroppedItemId = 1;
|
||||
private readonly Dictionary<int, DungeonMobDefinition> _mobDefinitions;
|
||||
|
||||
public DungeonSimulation(DungeonLayout layout, int tier, Dictionary<int, DungeonMobDefinition> mobDefinitions)
|
||||
public DungeonSimulation(DungeonLayout layout, int tier, Dictionary<int, DungeonMobDefinition> mobDefinitions, int bracketMin = 1)
|
||||
{
|
||||
Layout = layout;
|
||||
Tier = tier;
|
||||
BracketMin = bracketMin;
|
||||
_mobDefinitions = mobDefinitions;
|
||||
|
||||
SpawnMobs();
|
||||
@@ -105,7 +107,8 @@ public class DungeonSimulation
|
||||
var mobDef = SelectMobDefinition(mobSpawn.MobType, rng);
|
||||
if (mobDef == null) continue;
|
||||
|
||||
var stats = mobDef.GetStatsForTier(Tier);
|
||||
// Use bracket-aware stat scaling
|
||||
var stats = mobDef.GetStatsForTierAndBracket(Tier, BracketMin);
|
||||
|
||||
Mobs[mobSpawn.Id] = new MobInstance
|
||||
{
|
||||
|
||||
+1836
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SystemRevivalServer.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class DungeonBrowser : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "dungeon_instances",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Tier = table.Column<int>(type: "int", nullable: false),
|
||||
Seed = table.Column<int>(type: "int", nullable: false),
|
||||
LevelBracketMin = table.Column<int>(type: "int", nullable: false),
|
||||
LevelBracketMax = table.Column<int>(type: "int", nullable: false),
|
||||
CreatorCharacterId = table.Column<ulong>(type: "bigint unsigned", nullable: false),
|
||||
CreatorName = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
CreatorLevel = table.Column<int>(type: "int", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
LastActivity = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
PersistedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
|
||||
BossKilled = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
IsCleared = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
MobStateJson = table.Column<string>(type: "json", nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
ChestStateJson = table.Column<string>(type: "json", nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
LootChestStateJson = table.Column<string>(type: "json", nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
CreatorId = table.Column<ulong>(type: "bigint unsigned", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_dungeon_instances", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_dungeon_instances_dungeon_characters_CreatorId",
|
||||
column: x => x.CreatorId,
|
||||
principalTable: "dungeon_characters",
|
||||
principalColumn: "Id");
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_dungeon_instances_CreatorId",
|
||||
table: "dungeon_instances",
|
||||
column: "CreatorId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "dungeon_instances");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -735,6 +735,68 @@ namespace SystemRevivalServer.Migrations
|
||||
b.ToTable("dungeon_mob_loot_tables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Server.Data.Entities.DungeonPersistence", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("BossKilled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("ChestStateJson")
|
||||
.HasColumnType("json");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<ulong>("CreatorCharacterId")
|
||||
.HasColumnType("bigint unsigned");
|
||||
|
||||
b.Property<ulong?>("CreatorId")
|
||||
.HasColumnType("bigint unsigned");
|
||||
|
||||
b.Property<int>("CreatorLevel")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("CreatorName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("IsCleared")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<DateTime>("LastActivity")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<int>("LevelBracketMax")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<int>("LevelBracketMin")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("LootChestStateJson")
|
||||
.HasColumnType("json");
|
||||
|
||||
b.Property<string>("MobStateJson")
|
||||
.HasColumnType("json");
|
||||
|
||||
b.Property<DateTime?>("PersistedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<int>("Seed")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<int>("Tier")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatorId");
|
||||
|
||||
b.ToTable("dungeon_instances");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Server.Data.Entities.DungeonSpellDefinition", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
@@ -1613,6 +1675,15 @@ namespace SystemRevivalServer.Migrations
|
||||
b.Navigation("MobDefinition");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Server.Data.Entities.DungeonPersistence", b =>
|
||||
{
|
||||
b.HasOne("Server.Data.Entities.DungeonCharacter", "Creator")
|
||||
.WithMany()
|
||||
.HasForeignKey("CreatorId");
|
||||
|
||||
b.Navigation("Creator");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b =>
|
||||
{
|
||||
b.HasOne("Server.Data.Entities.DungeonCharacter", "Character")
|
||||
|
||||
@@ -14,6 +14,13 @@ public static class DungeonOpCodes
|
||||
public const int DUNGEON_ENTER_RESULT = 301;
|
||||
public const int DUNGEON_STATE = 302;
|
||||
public const int DUNGEON_LEAVE = 303;
|
||||
public const int DUNGEON_CLEARED = 304;
|
||||
|
||||
// Dungeon Browser (310-319)
|
||||
public const int DUNGEON_LIST_REQUEST = 310;
|
||||
public const int DUNGEON_LIST_RESPONSE = 311;
|
||||
public const int DUNGEON_CREATE = 312;
|
||||
public const int DUNGEON_JOIN = 313;
|
||||
|
||||
// Input (400-449)
|
||||
public const int DUNGEON_INPUT_MOVE = 400;
|
||||
@@ -35,7 +42,6 @@ public static class DungeonOpCodes
|
||||
public const int EVENT_LEVELUP = 502;
|
||||
public const int EVENT_LOOT = 503;
|
||||
public const int LOOT_RECEIVED = 160;
|
||||
public const int DUNGEON_CLEARED = 304;
|
||||
|
||||
// Inventory (250-259)
|
||||
public const int INVENTORY_REQUEST = 250;
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
using System.Security.Principal;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Server.Data.Entities;
|
||||
using Server.Data.Entities;
|
||||
using Server.Data.Enums;
|
||||
|
||||
|
||||
namespace Server.Data;
|
||||
|
||||
@@ -34,6 +33,7 @@ public sealed class GameDbContext : DbContext
|
||||
public DbSet<DungeonBeltItem> DungeonBeltItems => Set<DungeonBeltItem>();
|
||||
public DbSet<DeathChest> DeathChests => Set<DeathChest>();
|
||||
public DbSet<DeathChestItem> DeathChestItems => Set<DeathChestItem>();
|
||||
public DbSet<DungeonPersistence> DungeonInstances => Set<DungeonPersistence>();
|
||||
protected override void OnModelCreating(ModelBuilder b)
|
||||
{
|
||||
b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly);
|
||||
|
||||
@@ -120,19 +120,34 @@ public class DungeonMobDefinition
|
||||
/// </summary>
|
||||
public DungeonMobCombatStats GetStatsForTier(int tier)
|
||||
{
|
||||
return GetStatsForTierAndBracket(tier, 1); // Default to bracket 1 for backwards compatibility
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculate scaled stats for a specific dungeon tier and level bracket
|
||||
/// Level bracket scaling: each bracket adds 15% to base stats
|
||||
/// </summary>
|
||||
public DungeonMobCombatStats GetStatsForTierAndBracket(int tier, int bracketMin)
|
||||
{
|
||||
// Calculate bracket number (1-10 = bracket 1, 11-20 = bracket 2, etc.)
|
||||
int bracketNumber = Math.Max(1, (bracketMin - 1) / 10 + 1);
|
||||
|
||||
// Bracket scaling: each bracket adds 15% to base stats (compound)
|
||||
double bracketMultiplier = Math.Pow(1.15, bracketNumber - 1);
|
||||
|
||||
return new DungeonMobCombatStats
|
||||
{
|
||||
MaxHealth = (int)(BaseHealth * Math.Pow(HealthPerTier, tier - 1)),
|
||||
PhysicalDamage = (int)(BasePhysicalDamage * Math.Pow(DamagePerTier, tier - 1)),
|
||||
MagicDamage = (int)(BaseMagicDamage * Math.Pow(DamagePerTier, tier - 1)),
|
||||
Armor = (int)(BaseArmor * Math.Pow(ArmorPerTier, tier - 1)),
|
||||
MagicResist = (int)(BaseMagicResist * Math.Pow(ArmorPerTier, tier - 1)),
|
||||
MaxHealth = (int)(BaseHealth * Math.Pow(HealthPerTier, tier - 1) * bracketMultiplier),
|
||||
PhysicalDamage = (int)(BasePhysicalDamage * Math.Pow(DamagePerTier, tier - 1) * bracketMultiplier),
|
||||
MagicDamage = (int)(BaseMagicDamage * Math.Pow(DamagePerTier, tier - 1) * bracketMultiplier),
|
||||
Armor = (int)(BaseArmor * Math.Pow(ArmorPerTier, tier - 1) * bracketMultiplier),
|
||||
MagicResist = (int)(BaseMagicResist * Math.Pow(ArmorPerTier, tier - 1) * bracketMultiplier),
|
||||
MoveSpeed = MoveSpeed,
|
||||
AttackRange = AttackRange,
|
||||
AttackSpeed = AttackSpeed,
|
||||
AggroRange = AggroRange,
|
||||
LeashRange = LeashRange,
|
||||
XpReward = (int)(BaseXp * Math.Pow(XpPerTier, tier - 1)),
|
||||
XpReward = (int)(BaseXp * Math.Pow(XpPerTier, tier - 1) * bracketMultiplier),
|
||||
Resistances = Resistances
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Server.Data.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Persisted dungeon data for dungeons that become inactive but remain "open"
|
||||
/// </summary>
|
||||
[Table("dungeon_instances")]
|
||||
public class DungeonPersistence
|
||||
{
|
||||
[Key]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public int Tier { get; set; }
|
||||
public int Seed { get; set; }
|
||||
|
||||
// Level bracket
|
||||
public int LevelBracketMin { get; set; }
|
||||
public int LevelBracketMax { get; set; }
|
||||
|
||||
// Creator info
|
||||
public ulong CreatorCharacterId { get; set; }
|
||||
public string CreatorName { get; set; } = "";
|
||||
public int CreatorLevel { get; set; }
|
||||
|
||||
// Timestamps
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime LastActivity { get; set; }
|
||||
public DateTime? PersistedAt { get; set; }
|
||||
|
||||
// State
|
||||
public bool BossKilled { get; set; } = false;
|
||||
public bool IsCleared { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Serialized mob state (JSON) - only alive mobs with their positions/health
|
||||
/// </summary>
|
||||
[Column(TypeName = "json")]
|
||||
public string? MobStateJson { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Serialized chest state (JSON) - which chests are opened
|
||||
/// </summary>
|
||||
[Column(TypeName = "json")]
|
||||
public string? ChestStateJson { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Serialized loot chest state (JSON) - personal loot chests
|
||||
/// </summary>
|
||||
[Column(TypeName = "json")]
|
||||
public string? LootChestStateJson { get; set; }
|
||||
|
||||
// Navigation
|
||||
public virtual DungeonCharacter? Creator { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializable mob state for persistence
|
||||
/// </summary>
|
||||
public class PersistedMobState
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int DefinitionId { get; set; }
|
||||
public float X { get; set; }
|
||||
public float Y { get; set; }
|
||||
public int Health { get; set; }
|
||||
public bool IsAlive { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializable chest state for persistence
|
||||
/// </summary>
|
||||
public class PersistedChestState
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public bool IsOpened { get; set; }
|
||||
}
|
||||
Reference in New Issue
Block a user