游戏随机关卡跳转脚本概率计算疑似偏差问题排查
游戏退出随机关卡跳转的概率问题排查经历
我开发了一款游戏,设计了退出时触发骰子机制随机跳转至不同关卡的功能,用以下C#脚本实现该逻辑:
public string levelToLoad; // first level public bool levelSplit; //Do we split? public string levelToSplit; //second level public int splitLevelChance; //if the chance was 4/7, this should be the 4 public int SplitDenominator; //And this should be the 7 int normal = 0; //To keep count int split = 0; for (int i = 0; i < 2000; i++) //Run the test 2000 times { System.Random rnd = new System.Random(); int dice = rnd.Next(1, SplitDenominator + 1); //Roll a dice print(dice); if (dice <= splitLevelChance) { normal++; // SceneManager.LoadScene(levelToLoad); } else { split++; // SceneManager.LoadScene(levelToSplit); } } print("normal: " + normal); print("split:" + split);
问题出现与排查过程
- 脚本在1/4、1/8这类概率场景下测试运行正常,结果完全符合预期
- 但测试8/18概率时,我自行计算的预期值是normal约615、split约1385,可三次测试结果却和预期偏差很大:
- Test 1 - normal = 899, split = 1101
- Test 2 - normal = 879, split = 1121
- Test 3 - normal = 885, split = 1115
- 一开始我怀疑是脚本的概率计算逻辑出错了,反复检查代码后才发现,是我自己的预期值计算错误——8/18简化后是4/9,2000次测试的话normal的预期值应该是2000*(4/9)≈889,和实际测试结果完全吻合,脚本的逻辑是正确的。
内容的提问来源于stack exchange,提问作者Rachel Dockter
相关产品推荐
相关产品推荐

