如何正确开发概率系统?

时间:2015-11-17 00:41:54

标签: c++ random probability

所以我正在开发一款在线游戏,这款游戏的其中一个功能就像许多其他的MMORPG一样,它是一种降落系统。升级系统。

掉落系统决定杀死怪物时会从哪些物品中掉落。 升级系统决定某个项目是否成功升级到下一级别。

他们都需要能够使用概率来确定是否:

  1. 项目Drops
  2. 项目升级成功。
  3. 我开发了一个系统,可以生成一个0到100000之间的随机数。在这个系统中,上述任何一种情况的1%概率将由1000表示。同样,0.5%将是500 ...... 50%将是50000。

    以下是此代码的内容......

    int RandomValueInRange(const int start, const int end)
    {
       std::random_device rd;
       std::mt19937 generator(rd());
       const int stable_end = ((end < start) ? start : end);
       std::uniform_int_distribution<int> distribution(start, stable_end);
    
       return distribution(generator);
    }
    

    现在,如果物品掉落或升级,那么我只需要这样做......

    const int random_value = RandomValueInRange(0, 100000);
    const int probability = item.GetProbability();//This simply returns an integer stored in a config file which represents the probability of this item being dropped/upgraded.
    if(random_value <= probability)
    {
        std::cout << "Probability Success!" << endl;
    }
    else
    {
        std::cout << "Probability Failed!" << endl;
    }
    

    我希望上述方法能够奏效,但无论出于何种原因,它似乎都有问题......玩家可以轻松获得0.1%概率的物品(这种情况几乎不会发生!)。

    有没有人知道一个更好的系统,或者我如何改进这个系统以真正遵循概率准则......

2 个答案:

答案 0 :(得分:1)

std::random_device rd;
std::mt19937 generator(rd());
...
return distribution(generator);

我认为这里有问题,std c++ library可以让你统一分发 如果你重复使用random_device和mt19937,但每次都重新创建它们, 不应该如何使用它们。 保存此std::random_device rd以及此std::mt19937和此distribution

的某处

答案 1 :(得分:0)

好的,您的代码问题在于您选择0到100,000之间的随机数。任何人都可以获得1到100之间的运气,因为,如果你考虑一下,100就是一个相当大的数字而且不应该太难获得。

另外,如果你回到小学/小学(或任何你想称之为的)学校数学书籍,你会看到概率和机会&#39;章,一些问题如:

  

如果一个包中有6个球,3个红色,1个绿色和2个蓝色,那么选择蓝色的可能性是多少?

当然,你会回答2/6或1/3。在C ++中,可以将其更改为:

#include <iostream>
#include <ctime>
#include <algorithm>
#include <random>

using namespace std;


// Be sure to have this in to get a truly random number

class MoreProbability {


    // Be sure to have this in to get a truly random number



    void GetProbability(int min, int max, int probability) {
        const int arrayMax = max;
        int probabilityArray[100000];
        for (int i = 0; i < max; i++) {
            if (i >= 0 && i <= probability) {
                probabilityArray[i] = 1;
            }
            else {
                probabilityArray[i] = 0;
            }
        }
        // Arrays go from 0 to max-1 to account for the 0
        std::random_shuffle(&probabilityArray[0], &probabilityArray[max - 1]);

        // Check if the first element of the randomly shufffled array is equal to 1
        if (probabilityArray[0] == 1) {
            cout << "Probability Successful" << endl;
        }
        else {
            cout << "Probability Failed" << endl;
        }
    }
    int main() {
        srand(time(0));

        GetProbability(0, 100000, 100);

        return 0;
    }
};

它可能会产生StackOverflowException。要解决此问题,只需增加“堆栈预留大小”即可。

修改

<小时/> 根据结果​​更改代码后返回1或0,然后将其放入for循环中,重复1000次(我强 建议尝试此操作,因为它需要一段时间为了完成),我得到了1的输出,清楚地表明这段代码完美无缺。