Game experience level question
I have an algorithm que开发者_如何学运维stion related to XP levels in games:
I have a table that lists level numbers, and number of XPs in that level:
GameLevel ExperiencePointsInLevel
1 30
2 70
3 160
4 250
For each player, I only maintain their total XP, not any level info. Given a player's total XP, how do I determine the following via an algorithm (I'm using C# & LINQ)?
- Current level of person
- Number points the person has in this level
For example, if a player has 110 XPs, the answer would be:
- Level 3
- 10 XPs; (110-30-70 = 10)
Any ideas?
Cheers,
Dean
If experience points in level is changed to represent the total XP a player needs to reach that level.
Game Level Experience Points
1 0
2 100
3 200
4 400
A more functional approach with LINQ would be something like the following:
var playerlevel = ExperiencePointsTable
.Where(xpt => xpt.ExperiencePointsInLevel <= player.ExperiencePoints)
.Select(xpt => xpt.GameLevel)
.Max();
I think this simplifies the solution and avoids having to generate arrays for a look up.
Edit: fixed to check less than or equal to level.
To find out how many xp the player has to get to the next level you can use a similiar LINQ query.
var xpToNextLevel = (ExperiencePointsTable
.Where(xpt => xpt.ExperiencePointsInLevel > player.ExperiencePoints)
.Select(xpt => xpt.ExperiencePoints)
.Min()) - player.ExperiencePoints;
You can keep a list of the upper inclusive bound of each level (Level 1: 0-29, Level 2: 30-99, etc.) and perform a binary search for the input value:
var levels = new int[]
{
0 - 1,
30 + 0 - 1,
70 + 30 + 0 - 1,
160 + 70 + 30 + 0 - 1,
250 + 160 + 70 + 30 + 0 - 1
};
var input = 110;
var level = Array.BinarySearch(levels, input);
if (level < 0)
level = ~level;
Console.WriteLine("Level: {0}", level);
Console.WriteLine("Points: {0}", input - (levels[level - 1] + 1));
(untested; may contain off-by-one errors)
If the table is sorted, then do something like this:
foreach(DataRow row in table.Rows)
{
if(xp > (int)row["XP"])
{
xp -= (int)row["XP"];
} else {
Console.WriteLine("Level: " + row["Level"] + " with " + xp + " xp");
break;
}
}
Same idea with whatever data structure you're using
精彩评论