Need for predictable random generator

前端 未结 30 1057
情话喂你
情话喂你 2020-11-27 09:04

I\'m a web-game developer and I got a problem with random numbers. Let\'s say that a player has 20% chance to get a critical hit with his sword. That means, 1 out of 5 hits

30条回答
  •  温柔的废话
    2020-11-27 09:30

    If you want a distribution that discourages repeat values, you could use a simple repeat rejection algorithm.

    e.g.

    int GetRand(int nSize)
    {
        return 1 + (::rand() % nSize);
    }
    int GetDice()
    {
        static int nPrevious=-1;
        while (1) {
            int nValue = GetRand(6);
            // only allow repeat 5% of the time
            if (nValue==nPrevious && GetRand(100)<95)
                continue;
            nPrevious = nValue;
            return nValue;
        }
    }
    

    This code rejects repeat values 95% of the time, making repeats unlikely but not impossible. Statistically it is a bit ugly, but it will probably produce the results you want. Of course, it won't prevent a distribution like "5 4 5 4 5". You could get fancier and reject the second last (say) 60% of the time and third last (say) 30%.

    I'm not recommending this as good game design. Simply suggesting how to achieve what you want.

提交回复
热议问题