random.org 统一

问题描述 投票:0回答:1

我正在尝试从在线服务中获取随机数,我听说了带有 Unity 的 Random.org,但我不知道如何制作它 有没有示例代码可以制作? 我写了这段代码

https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new

但出现错误:

?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new:HTTP 错误:HTTP/1.1 403 禁止

void Start()
{
    // A correct website page.
    StartCoroutine(GetRequest("https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new"));
}

IEnumerator GetRequest(string uri)
{
    using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
    {
        // Request and wait for the desired page.
        yield return webRequest.SendWebRequest();

        string[] pages = uri.Split('/');
        int page = pages.Length - 1;

        switch (webRequest.result)
        {
            case UnityWebRequest.Result.ConnectionError:
            case UnityWebRequest.Result.DataProcessingError:
                Debug.LogError(pages[page] + ": Error: " + webRequest.error);
                break;
            case UnityWebRequest.Result.ProtocolError:
                Debug.LogError(pages[page] + ": HTTP Error: " + webRequest.error);
                break;
            case UnityWebRequest.Result.Success:
                Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
                break;
        }
    }
}
c# unity-game-engine random game-engine game-development
1个回答
0
投票

我是来自 Random.org 的 Mads。您的方法存在一些问题:

(1) 您正在使用旧的(且过时的)Random.org API (https://www.random.org/clients/http/)。旧的 API 仍在运行,但它不提供与新的(自 2016 年起)API (https://api.random.org) 相同的可用性,这就是为什么您有时会看到请求被拒绝服务器。

(2) 您一次仅请求一个随机数。这是低效的,因为您需要承担单个随机值的 HTTP 请求的全部开销。除非您只需要一个随机值,否则它也违反了 Random.org 使用旧 API 的建议:https://www.random.org/clients/

最好的解决方案是使用 Random.org 的新 API,它具有更好的可用性。新的 API 还具有官方 .NET 库,Unity 支持该库。该库具有缓存功能,这意味着您可以避免上面的问题(2)。该库位于:https://github.com/RandomOrg/JSON-RPC-.NET

使用此库,您可以使用如下代码(改编自官方文档)来生成 [1,6] 范围内的整数(就像您的代码的预期目的):

RandomOrgClient roc = RandomOrgClient.GetRandomOrgClient(YOUR_API_KEY_HERE);
RandomOrgCache<int[]> c = roc.CreateIntegerCache(1, 1, 6);
while (true) {
    try {
        int[] randoms = c.Get();
        Console.WriteLine(string.Join(",", randoms));
    } catch (RandomOrgCacheEmptyException) {
        // handle lack of true random number here
        // possibly use a pseudo random number generator
    }
}

注意:

CreateIntegerCache()
的第一个参数是您希望每个
Get()
调用返回的随机值的数量。我保留了对
Join()
的调用,以防您想一次生成多个值。

附注您可以在这里找到 Random.org 库的完整列表:https://api.random.org/json-rpc/4/source-code

© www.soinside.com 2019 - 2024. All rights reserved.