c# - 创建两个不同的随机变量
问题描述
我正在制作一种扑克游戏,你和一个 ai 对战,你们都会得到一组随机数。在为它创建方法时,我注意到程序总是为两者创建相同的数组。
public short[] GenerateNumbers(short[] playerNumbers) //The generate numbers method creates an array of random numbers
{
Random randNumb = new Random(); //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array
playerNumbers = new short[5]; //Stating the length of the player's array
for (int i = 0; i < playerNumbers.Length; i++) //This loop creates random numbers for every position in the array
{
playerNumbers[i] = (short)randNumb.Next(1, 9);
}
playerOneHand = playerNumbers;
return playerOneHand;
}
public short[] GenerateAINumbers(short[] aiNumbers) //The generate numbers method creates an array of random numbers
{
Random randAINumb = new Random(); //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array
aiNumbers = new short[5]; //Stating the length of the player's array
for (int j = 0; j < aiNumbers.Length; j++) //This loop creates random numbers for every position in the array
{
aiNumbers[j] = (short)randAINumb.Next(1, 9);
}
aiHand = aiNumbers;
return aiHand;
}
解决方案
您可以创建实例级 Random 对象:
private Random rnd = new Random();
public short[] GenerateNumbers(short[] playerNumbers) {...}
public short[] GenerateAINumbers(short[] aiNumbers) {...}
你可以在你的方法中使用这个 rnd 对象,而不是总是创建一个新对象。
推荐阅读
- java - 杰克逊 XML 映射器强制小写 XML 标记
- c++ - cout 字符串不会在屏幕上打印任何内容
- api - 如何通过 AppDynamics API 获取应用流程图数据?
- android - 如何在 Android Telnet 客户端设备上更改屏幕大小
- javascript - 如何在 Vue-router 路由中加载非 Vue.js 组件,特别是 Backbone Marionette Views
- powershell - 如何修复 Powershell 脚本的不明确参数
- javascript - 如何在 ReactJs 中包含外部 JavaScript 库(Topol.io)?
- c# - 在对类属性使用驼峰式大小写时强制字典键的小写 JSON 序列化
- c# - 如何让 Rust FFI 返回结构数组或更新内存?
- azure - 我需要选择什么认知服务才能进行 Azure VM API 调用?