2015-06-19 17 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,所以其他應用程序/線程可以使用處理器!