2014-09-06 56 views
-3

正確我想知道如何儘可能使用已經被讀取的代碼或有效的方式來做到這一點。Vb控制檯問題如何

我希望能夠使用位置變量而不必將其寫出數百次。 希望你明白我在說什麼。我希望能夠離開商店,並回到這個console.writeline(「你想去哪兒」)部分。

 Console.WriteLine("where would you like to go") 
     Console.WriteLine("1 - The shop") 
     location = Console.ReadLine() 
    Loop Until location = "1" 
    Console.WriteLine("") 
    Console.WriteLine("") 
    Console.WriteLine("") 
    Console.WriteLine("***********************************The Shop***********************************") 
    Console.ReadLine() 
    Console.WriteLine("") 
    Console.writeline("Shopkeeper: how can I help you") 

回答

1

我會建議你嘗試一種更加結構化的方法。使用一個名爲Location的新類,其中包含有關每個位置的信息(示例中包含名稱和可能的目標列表)。這當然可以通過可能的相互作用和其他方式進一步提高。

Public Class Location 
    Public Property Name As String 
    Public Property Destinations As List(Of String) 
    Public Sub New(Name As String, Destinations As String()) 
     Me.Name = Name 
     Me.Destinations = New List(Of String) 
     Me.Destinations.AddRange(Destinations) 
    End Sub 
End Class 

您首先在遊戲中製作位置列表。我做了三個,街道,商店和商店的後房(神祕!)。 在每次迭代中,您都會顯示一個列表,其中包含您製作的對象的位置,並讓用戶選擇一個位置。然後您根據名稱更改位置。
這樣你可以輕鬆地添加位置和互連。
你並不是真的想硬編碼用戶可以採取的每一步。

Module Module1 

    Sub Main() 
     'Create locations 
     Dim Locations As New List(Of Location) 
     Locations.Add(New Location("Shop", {"Street", "Back Room"})) 
     Locations.Add(New Location("Street", {"Shop"})) 
     Locations.Add(New Location("Back Room", {"Shop"})) 
     'Define a starting location 
     Dim CurrentLocation As String = "Street" 
     Do 
      Console.WriteLine("You are at: " & CurrentLocation) 
      Console.WriteLine("Destinations: ") 
      'Bit of Linq to select the location by name from your defined locations 
      Dim ThisLocation As Location = (From l As Location In Locations Where l.Name = CurrentLocation Select l).First 
      'Display the possible destinations from here 
      For i = 0 To ThisLocation.Destinations.Count - 1 
       Console.WriteLine(String.Format("-{0}- {1}", (i + 1).ToString, ThisLocation.Destinations(i))) 
      Next 
      'Read user input for a the destination he wants to travel to 
      Dim NewLocation As Integer = -1 
      Do 
       Console.Write(" Go to: ") 
       Integer.TryParse(Console.ReadLine, NewLocation) 
      Loop Until NewLocation >= 1 AndAlso NewLocation <= ThisLocation.Destinations.Count 
      'Change the current location 
      CurrentLocation = ThisLocation.Destinations(NewLocation - 1) 
     Loop 

    End Sub 

End Module