2015-06-19 18 views
0

我正在制作一个基于文本的游戏,我想用一个文本打印缓慢进行介绍(字符由字符差异〜100ms)我试着做一个循环,通过字符串循环并逐个打印字符,但我需要一个中间计时器,即使在谷歌的帮助下我也无法实现。所以我需要帮助制作计时器或其他算法以便慢慢打印字符串。 我的代码:打印字符串字符char /定时器

static void PrintSlowly(string print) 
{ 
    foreach(char l in print) { 
     Console.Write(l); 
     //timer here 
    } 
    Console.Write("\n"); 
} 
+1

睡100ms也许?您的游戏是否以任何方式进行多线程? –

+1

'Thread.Sleep(100)'? – stefankmitph

+0

@ bali182你会在学习问题的地方制作一个多线程的游戏软件吗? –

回答

1

讨厌,讨厌的廉价的解决方案:

static void PrintSlowly(string print) 
{ 
    foreach(char l in print) { 
     Console.Write(l); 
     Thread.sleep(10); // sleep for 10 milliseconds  
    } 
    Console.Write("\n"); 
} 

既然你可能不那么在意性能,你可以用这个去。但请记住,Thread.Sleep is pretty wasteful

+0

Thread.sleep中的参数是什么? milisecs?秒? – Ravid

+0

毫秒,就像背后的注释说明 –

+0

为什么线程如此糟糕?没有真正理解线程(我不得不) – Ravid

1

基于apomene的解决方案,我会选择一个(实时)基于定时器的解决方案,因为Thread.Sleep是相当不准确的。

static void PrintSlowly(string print) 
{ 
    int index = 0; 
    System.Timers.Timer timer = new System.Timers.Timer(); 

    timer.Interval = 100; 
    timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, args) => 
    { 
     if (index < print.Length) 
     { 
      Console.Write(print[index]); 
      index++; 
     } 
     else 
     { 
      Console.Write("\n"); 
      timer.Enabled = false; 
     } 
    }); 

    timer.Enabled = true; 
} 

计时器将每100毫秒回来一次,选取下一个字符并打印出来。如果没有更多的字符可用,它将打印返回并禁用它自己。我使用lambda表达式使用匿名处理方法编写它 - 而不是最干净的方式。这只是关于原则。 此实现与您的应用程序并行运行,因此它不会阻止您的代码执行。如果你想这样做,不同的方法可能会更好。

或者 - 作为修改apomene的解决方案而不需要等待 - 您可以使用ManualResetEvent

static System.Timers.Timer delay = new System.Timers.Timer(); 
static AutoResetEvent reset = new AutoResetEvent(false); 

private static void InitTimer() 
{ 
    delay.Interval = 100; 
    delay.Elapsed += OnTimedEvent; 
    delay.Enabled = false; 
} 

private static void OnTimedEvent(object sender, ElapsedEventArgs e) 
{ 
    ((System.Timers.Timer)sender).Enabled = false; 
    reset.Set(); 
} 

static void PrintSlowly2(string print) 
{ 
    InitTimer(); 

    foreach (char l in print) 
    { 
     Console.Write(l); 
     delay.Enabled = true; 

     reset.WaitOne(); 
    } 
    Console.Write("\n"); 
} 

它等待使用AutoResetEvent,所以其他应用程序/线程可以使用处理器!