簡體   English   中英

如何正確開發概率系統?

[英]How do I properly develop a Probability System?

因此,我正在開發在線游戲,該游戲的功能之一(如許多其他MMORPG一樣)是放下系統和升級系統。

掉落系統決定殺死怪物時會掉落哪些物品。 升級系統決定某個項目是否將成功升級到下一個級別。

他們都需要能夠使用概率來確定是否:

  1. 物品掉落
  2. 項成功升級。

我已經開發了一個系統,該系統生成一個介於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%概率的物品(幾乎永遠不會發生!)。

有誰知道一個更好的系統,或者我如何改善這個系統以真正遵循概率准則。

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

我認為這里存在問題,如果您確實重用random_device和mt19937,則std c++ library會為您提供統一的分配,但是每次都重新創建它們,這不是應該使用它們的方式。 將此std::random_device rd和此std::mt19937以及此distribution

好的,所以代碼的問題是您選擇的是0到100,000之間的隨機數。 幸運的話,任何人都可以得到1到100之間的數字,因為如果您考慮一下,100是一個很大的數字,應該不會太難。

另外,如果您返回小學/初中(或任何您想稱呼的)學校數學書籍,您將在“概率和機會”一章中看到一些問題,例如:

如果一個袋子里有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的輸出,清楚表明該代碼段完美運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM