开发者

Javascript points calculating system

I trying to create a points calculating system with javascript, but the problem is with the mathematical part. I have saved on the server the points number, and based on that number I want to decide the level. Sorry for my bad english, I cant explain very well :D. I want something like: level 1 need 0 points level 2 needs 100 points level 3 needs 240 points level 4 needs 420 points level 5 needs 640 points and so on.... I need a mathematical function to calculate each level with it. Something that if I know the level to calculate the p开发者_JAVA技巧oints needed, and if I know only the points to calculate the level.


To generate the series you've provided use:

function getPoints(level)
{
  return 20*(level-1)*(level+3);
}

To get the level from the points is a bit more tricky, you need to invert the above formula using the quadratic formula and then take the positive solution:

function getLevel(points)
{
  var level = -1 + Math.sqrt(4 + points/20);

  // Round down to nearest level
  return Math.floor(level);
}

Also, in the future try and make your questions clearer. As you can see three people (at least) misunderstood your question - it wasn't clear that you set of levels was a mathematical series.


var levels = {
1: 0,
2: 100,
3: 240,
4: 420,
5: 640}
function get_level(points){
    for (level in levels){
       if (points < levels[level]){
          return level - 1;
       }
    }
}

This simply takes the levels hash and itenerates through the levels, until the points is higher than the level's minimum, returning the last level.


ummm, I have a vague idea of what you're going for

var levels = [0, 100, 240, 420, 640];

function GetLevel(points)
{
    for(i == levels.length - 1; i >= 0; i--)
    {
        if (points >= levels[i]) return i + 1;        
    }        
}

points to next level

function PointsToNextLevel(currentPoints)
{
    var level = GetLevel(currentPoints);
    if (level == levels.length) return 0;
    return levels[level - 1] - currentPoints;
}


this function should solve your problem and, to me, seems very easy to understand:

function getLevel(points) 
{
    var levels = [0,100, 240, 420, 640];
    var maxLevel = levels.length;
    var i;
    for (i=0;i<maxLevel;i++) {
      if (levels[i]>points) return i;
    }
    return maxLevel;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜