using System.Linq;
namespace NWN.Anvil.Samples
{
public sealed class ExpTableEntry : ITwoDimArrayEntry
{
public int Level { get; private set; }
public int XP { get; private set; }
public int RowIndex { get; init; }
public void InterpretEntry(TwoDimArrayEntry entry)
{
Level = entry.GetInt("Level").GetValueOrDefault(0);
XP = entry.GetInt("XP").GetValueOrDefault(0);
}
}
[ServiceBinding(typeof(XPReportService))]
public class XPReportService
{
private readonly TwoDimArray<ExpTableEntry> expTable = NwGameTables.GetTable<ExpTableEntry>("exptable.2da")!;
public XPReportService()
{
NwModule.Instance.OnClientEnter += OnClientEnter;
}
private void OnClientEnter(ModuleEvents.OnClientEnter onClientEnter)
{
NwPlayer player = onClientEnter.Player;
NwCreature? creature = player.ControlledCreature;
if (creature == null)
{
return;
}
int nextLevel = GetLevelFromXp(creature.Xp) + 1;
if (nextLevel > MaxLevel)
{
return;
}
player.SendServerMessage($"Next level up: {GetXpForLevel(nextLevel) - creature.Xp}");
}
public int MaxLevel => expTable[^1].Level;
public int GetXpForLevel(int level)
{
return expTable.First(entry => entry.Level == level).XP;
}
public int GetLevelFromXp(int xp)
{
int level = 1;
foreach (ExpTableEntry entry in expTable.Rows)
{
if (entry.XP > xp)
{
break;
}
level = entry.Level;
}
return level;
}
}
}