C#游戏中NPC的异步行为

dur*_*ill 9 .net c# mono asynchronous c#-5.0

这个问题与这个问题有关(使用C#5异步来等待在多个游戏帧上执行的事情).

上下文

当Miguel de Icaza在Alt-Dev-Conf 2012上首次为游戏提供C#5异步框架时,我真的很喜欢使用asyncawait处理"脚本" 的想法(可以这么说,因为它们在c#中,在我的情况下,编译---在时间上,但无论如何编译)在游戏中.

即将推出的Paradox3D游戏引擎似乎也依赖于异步框架来处理脚本,但从我的角度来看,这个想法和实现之间存在着真正的差距.

链接的相关问题中,有人使用awaitNPC执行一系列指令,而游戏的其余部分仍在运行.

理念

我想更进一步,允许NPC同时执行多个操作,同时以顺序方式表达这些操作.有点像:

class NonPlayableCharacter 
{
    void Perform()
    {
        Task walking = Walk(destination); // Start walking
        Task sleeping = FallAsleep(1000); // Start sleeping but still walks
        Task speaking = Speak("I'm a sleepwalker"); // Start speaking
        await walking; // Wait till we stop moving.
        await sleeping; // Wait till we wake up.
        await speaking; // Wait till silence falls
    }
}
Run Code Online (Sandbox Code Playgroud)

要做到这一点,我用乔恩斯基特的为妙,因为前所未有的回答相关的问题.

履行

我的玩具实现包含两个文件,NPC.cs和Game.cs NPC.cs:

using System;
using System.Threading.Tasks;

namespace asyncFramework
{
    public class NPC
    {
        public NPC (int id)
        {
            this.id = id;

        }

        public async void Perform ()
        {
                    Task babbling = Speak("I have a superpower...");
            await Speak ("\t\t\t...I can talk while talking!");
            await babbling; 
            done = true;
        }

        public bool Done { get { return done; } }

        protected async Task Speak (string message)
        {
            int previousLetters = 0;
            double letters = 0.0;
            while (letters < message.Length) {
                double ellapsedTime = await Game.Frame;
                letters += ellapsedTime * LETTERS_PER_MILLISECOND;
                if (letters - previousLetters > 1.0) {
                    System.Console.Out.WriteLine ("[" + this.id.ToString () + "]" + message.Substring (0, (int)Math.Floor (Math.Min (letters, message.Length))));
                    previousLetters = (int)Math.Floor (letters);
                }
            }
        }

        private int id;
        private bool done = false;
        private readonly double LETTERS_PER_MILLISECOND = 0.002 * Game.Rand.Next(1, 10);
    }
}
Run Code Online (Sandbox Code Playgroud)

Game.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace asyncFramework
{
    class Game
    {
        static public Random Rand { 
            get { return rand; }
        }

        static public Task<double> Frame {
            get { return frame.Task; }
        }

        public static void Update (double ellapsedTime)
        {
            TaskCompletionSource<double> previousFrame = frame; // save the previous "frame"
            frame = new TaskCompletionSource<double> (); // create the new one
            previousFrame.SetResult (ellapsedTime); // consume the old one
        }

        public static void Main (string[] args)
        {
            int NPC_NUMBER = 10; // number of NPCs 10 is ok, 10000 is ko
            DateTime currentTime = DateTime.Now; // Measure current time
            List<NPC> npcs = new List<NPC> (); // our list of npcs
            for (int i = 0; i < NPC_NUMBER; ++i) { 
                NPC npc = new NPC (i); // a new npc
                npcs.Add (npc); 
                npc.Perform (); // trigger the npc actions
            }
            while (true) { // main loop
                DateTime oldTime = currentTime;
                currentTime = DateTime.Now;
                double ellapsedMilliseconds = currentTime.Subtract(oldTime).TotalMilliseconds; // compute ellapsedmilliseconds
                bool allDone = true;
                Game.Update (ellapsedMilliseconds); // generate a new frame
                for (int i = 0; i < NPC_NUMBER; ++i) {
                    allDone &= npcs [i].Done; // if one NPC is not done, allDone is false
                }
                if (allDone) // leave the main loop when all are done.
                    break;
            }
            System.Console.Out.WriteLine ("That's all folks!"); // show after main loop
        }

        private static TaskCompletionSource<double> frame = new TaskCompletionSource<double> ();
        private static Random rand = new Random ();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的实现!

问题

但是,它似乎没有按预期工作.

更准确地说,NPC_NUMBER为10,100或1000,我没有问题.但是在10,000或以上,该程序不再完成,它写了一段时间的"说话"线,然后没有更多的东西在控制台上.虽然我不是想在我的游戏中同时拥有10,000个NPC,但它们也不会写入愚蠢的对话框,而且还会移动,动画,加载纹理等等.所以我想知道我的实现有什么问题,如果我有机会修复它.

我必须确切地说代码是在Mono下运行的.此外,"有问题"的价值可能会在您的位置有所不同,它可能是计算机特定的东西.如果问题似乎无法在.Net下重现,我会在Windows下尝试.

编辑

在.Net中,它运行高达1000000,虽然它需要时间来初始化,但它可能是Mono特定的问题.Debugguer数据告诉我确实有NPC没有完成.遗憾的是,没有关于为什么的信息.

编辑2

在Monodevelop下,在没有调试器的情况下启动应用程序似乎可以解决问题.但不知道为什么......

结束词

我意识到这是一个非常非常冗长的问题,我希望你能花时间阅读它,我真的很想知道我做错了什么.

非常感谢你提前.

Eri*_*rik 1

不确定这是否相关,但这句话对我来说很突出:

allDone &= npcs [i].Done; // if one NPC is not done, allDone is false
Run Code Online (Sandbox Code Playgroud)

我建议等待您的Perform方法。由于您希望所有 NPC 异步运行,因此请将它们添加Perform Task到列表中并用于Task.WaitAll(...)完成。

反过来你可以做这样的事情:

var scriptList = new List<Task>(npcs.Count);

for (int i = 0; i < NPC_NUMBER; ++i) 
{
  var scriptTask = npcs[i].Perform();
  scriptList.Add(scriptTask);

  scriptTask.Start();
}

Task.WaitAll(scriptList.ToArray());
Run Code Online (Sandbox Code Playgroud)

只是一些值得深思的东西。

我已经await/async在 MonoTask库中使用了关键字,没有出现任何问题,所以我不会这么快就指责 Mono。