2015-10-19 58 views
1

當我按下一個鍵時,它會給我所有與該鍵有關的文本,而不僅僅是第一個WriteLine基本C#文本冒險破解

例如,當我按下Q甚至在第一個屏幕上,它說

"the door opens and you are blinded by the sun" 
"you walk to the town and are taken back to your cell" 

而不是僅僅把我送到下一個決策點。

class Program 
{ 
    static void Main(string[] args) 
    { 
     //Int 

     //String 

     Console.WriteLine("you find yourself in a dark room"); 
     Thread.Sleep(1000); 
     Console.WriteLine("In front of you is a door"); 
     Thread.Sleep(1000); 
     Console.WriteLine("Press 'W' to go through"); 
     ConsoleKeyInfo key = Console.ReadKey(true); 
     if (key.Key == ConsoleKey.W) 
     { 
      Console.WriteLine("You enter a room with two doors on either side"); 
      Thread.Sleep(1000); 
     } 
     Console.WriteLine("Press 'Q' to go left or 'E' to go right"); 
     { 
      if (key.Key == ConsoleKey.E) 
      { 
       Console.WriteLine("You enter the room to the right and are eaten by a grue"); 
      } 
      else if (key.Key == ConsoleKey.Q) 
      { 
       Console.WriteLine("The door opens and you are blinded by the sun"); 
       Thread.Sleep(1000); 
       Console.WriteLine("You walk down the road and come to a fork in it"); 
      } 
      Thread.Sleep(1000); 
      Console.WriteLine("Press 'Q' to go left, 'E' to go right, or 'W' to pick up the fork!"); 
      if (key.Key == ConsoleKey.Q) 
      { 
       Console.WriteLine("You walk to a town and are taken back to your cell by the guards"); 

      } 
     } 
     if (key.Key == ConsoleKey.E) 
     { 
      Console.WriteLine("You escape into the mountains! you win! "); 

     } 
     else if (key.Key == ConsoleKey.W) 
     { 
      Console.WriteLine("you pick up the fork unravelling space and time. You monster."); 
     } 
     Console.ReadLine(); 
    } 
} 

我在做什麼錯在這裏?

+2

那麼你只調用'ReadKey'一次...雖然你正在測試'W'被按下,如果第一個鍵*不是''W',你只是不顯示「兩扇門的房間」......你想在那裏發生什麼?你想循環,直到用戶*按下'W'?它不會幫助你的代碼沒有很好的格式化,並且你有一個沒有明顯原因的嵌套塊(在第一個「按Q向左走等」之後) –

+4

_巨大的代碼牆會造成10點傷害!_ – MickyD

+0

此代碼中的縮進是不可思議的:-) 不知道它是否因爲您沒有嘗試使它更清潔 –

回答

4

您需要一個key = Console.ReadKey(true);就在之間每決策點。例如

0

開爾文賴的答案當然是正確的,你已經收到了一個按鍵,用於整個代碼的key.Key每個測試。你永遠不會讓用戶輸入任何東西。

通過使用IDE中的內置調試器逐步調試代碼,您可以很容易地找到相應的代碼。

不管怎樣,回到問題...

你,你已經把那沒有任何意義,而實際上只是掩蓋正在發生的事情表達阻斷少數情況下。當你在一個表達式中詢問用戶的問題時,你的答案(你永遠不會實際得到的 - 參考主要問題)在外部塊中處理,這會讓人困惑。

您的格式已遍佈全球。當你看起來已經超出了自己的方式使其複雜化時,你如何期望能夠理解你的代碼?

風格不談,你的程序是一個非遞歸決策樹,分支之間不存在任何連接。如果你想添加一個循環回到以前的房間......繁榮,你必須從這一點複製整個樹。

下面是一些可以解決這個問題的方法。

首先,鍵盤互動。編寫一個方法,您可以使用有效密鑰列表進行調用,然後循環等待其中一個密鑰出現。當你有決定點提供給用戶時,用有效密鑰列表調用該方法。不要忘了包含一些突破和退出程序的方式,儘管優秀的舊Ctrl-C退出將起作用,除非您禁用它。

接下來,給出一些想法,把每個房間作爲一個對象。每一個都需要一些基本信息:

  • 的身份 - 一些通常,如果你喜歡
  • 房間的描述名稱/局面
  • 接受的按鍵,它們的描述和他們採取的列表你

有了,你可以寫一個外環,是以當前房間,顯示說明,給出了選項,並等待用戶輸入一些東西,然後選擇適當的隔壁房間。一旦你有了這些,只需要設置你希望它工作的任何房間清單。

當然,它然後允許你有房間循環,分支等,因爲而不是一棵直樹,你現在有一個地圖。

當然,如果你使用的是數據結構而不是代碼,那麼改變一般流程就變得多了更簡單。添加一個房間只是增加一些額外的信息到房間列表中,並通過另一個房間的選項列表來連接它。