2017-02-18 3 views
-2
Public Function Seeing_Connected_Counties(To_Button As Button, Initial_Button As Button) 
    Dim AdjcentCounties(,) As Button = New Button(,) {{Derbyshire, West_Yorkshire, South_Yorkshire, Nottinghamshire, Leicestershire, Warwickshire, Staffordshire, Cheshire, Manchester}, {Buckinhamshire, Hertfordshire, London, Berkshire, Oxfordshire, Northamptonshire, Bedfordshire, Scapegoat, Scapegoat}, {Hertfordshire, Cambridgeshire, Essex, London, Buckinhamshire, Bedfordshire, Scapegoat, Scapegoat, Scapegoat}, {Bedfordshire, Cambridgeshire, Hertfordshire, Buckinhamshire, Northamptonshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cambridgeshire, Lincolnshire, Norfolk, Suffolk, Essex, Hertfordshire, Bedfordshire, Northamptonshire, Scapegoat}, {Northamptonshire, Cambridgeshire, Bedfordshire, Buckinhamshire, Oxfordshire, Warwickshire, Leicestershire, Scapegoat, Scapegoat}, {Herefordshire, Gloucestershire, Worcestershire, Shropshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Worcestershire, Warwickshire, Gloucestershire, Herefordshire, Shropshire, Staffordshire, Scapegoat, Scapegoat, Scapegoat}, {Warwickshire, Northamptonshire, Leicestershire, Oxfordshire, Gloucestershire, Worcestershire, Staffordshire, Derbyshire, Scapegoat}, {Shropshire, Cheshire, Staffordshire, Worcestershire, Herefordshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Staffordshire, Cheshire, Derbyshire, Warwickshire, Worcestershire, Shropshire, Scapegoat, Scapegoat, Scapegoat}, {Leicestershire, Nottinghamshire, Lincolnshire, Northamptonshire, Warwickshire, Derbyshire, Scapegoat, Scapegoat, Scapegoat}, {Lincolnshire, East_Yorkshire, South_Yorkshire, Nottinghamshire, Leicestershire, Cambridgeshire, Norfolk, Scapegoat, Scapegoat}, {Nottinghamshire, Lincolnshire, Leicestershire, Derbyshire, South_Yorkshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cheshire, Merseyside, Manchester, Derbyshire, Staffordshire, Shropshire, Scapegoat, Scapegoat, Scapegoat}, {South_Yorkshire, North_Yorkshire, East_Yorkshire, Lincolnshire, Nottinghamshire, Derbyshire, West_Yorkshire, Scapegoat, Scapegoat}, {Merseyside, Lancashire, Manchester, Cheshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Manchester, West_Yorkshire, Derbyshire, Cheshire, Merseyside, Lancashire, Scapegoat, Scapegoat, Scapegoat}, {West_Yorkshire, North_Yorkshire, South_Yorkshire, Derbyshire, Manchester, Lancashire, Scapegoat, Scapegoat, Scapegoat}, {East_Yorkshire, North_Yorkshire, Lincolnshire, South_Yorkshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {North_Yorkshire, County_Durham, East_Yorkshire, South_Yorkshire, West_Yorkshire, Lancashire, Cumbria, Scapegoat, Scapegoat}, {Lancashire, Cumbria, North_Yorkshire, West_Yorkshire, Manchester, Merseyside, Scapegoat, Scapegoat, Scapegoat}, {Cumbria, Northumberland, County_Durham, North_Yorkshire, Lancashire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {County_Durham, Northumberland, North_Yorkshire, Cumbria, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Northumberland, Cumbria, County_Durham, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cornwall, Devon, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Devon, Cornwall, Somerset, Dorset, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Somerset, Devon, Dorset, Whiltshire, Gloucestershire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Dorset, Devon, Somerset, Whiltshire, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Hampshire, Dorset, Whiltshire, Berkshire, Surrey, West_Sussex, Isle_Of_White, Scapegoat, Scapegoat}, {Isle_Of_White, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Whiltshire, Somerset, Dorset, Hampshire, Berkshire, Gloucestershire, Oxfordshire, Scapegoat, Scapegoat}, {Gloucestershire, Herefordshire, Worcestershire, Warwickshire, Oxfordshire, Whiltshire, Somerset, Scapegoat, Scapegoat}, {West_Sussex, Surrey, East_Sussex, Kent, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {East_Sussex, West_Sussex, Kent, Surrey, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Kent, East_Sussex, Surrey, London, Essex, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {London, Surrey, Berkshire, Buckinhamshire, Hertfordshire, Essex, Kent, Scapegoat, Scapegoat}, {Essex, Kent, London, Hertfordshire, Cambridgeshire, Suffolk, Scapegoat, Scapegoat, Scapegoat}, {Suffolk, Essex, Cambridgeshire, Norfolk, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Norfolk, Suffolk, Cambridgeshire, Lincolnshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Surrey, Kent, West_Sussex, Hampshire, Berkshire, London, Scapegoat, Scapegoat, Scapegoat}, {Berkshire, London, Surrey, Hampshire, Whiltshire, Oxfordshire, Buckinhamshire, Scapegoat, Scapegoat}, {Oxfordshire, Berkshire, Whiltshire, Gloucestershire, Warwickshire, Northamptonshire, Buckinhamshire, Scapegoat, Scapegoat}} 
    Dim N As Integer = 1 
    Dim N_button As Button = Initial_Button 
    Dim T_button As Button 
    For I = 0 To 42 
     If N_button Is AdjcentCounties(I, 0) Then 
      For f = 0 To 8 
       T_button = AdjcentCounties(I, f) 
       If T_button.BackColor = To_Button.BackColor Then 
        If T_button Is To_Button Then 
         Return True 
        ElseIf T_button Is Scapegoat Then 
         N_button = AdjcentCounties(I, N) 
         N += 1 
         If N >= 8 Then 
          N = 0 
         End If 
         I = 0 
         Exit For 
        End If 
       End If 
      Next 
     End If 
    Next 
    Return False 
End Function 

Для моего вычислительного проекта я делаю риск версии, который требуется после того, как игрок атакует, чтобы позволить им перемещать войска из одного уезда в другой, если они связаны округами, которые принадлежат тем же игроком (обозначенным в моей игре обратным цветом кнопки). Я играл круглый с этим кодом выше примерно за последние 4 часа иша и не сделал никакого прогресса вашей помощь будет оценена благодаряПоиск нескольких времен, хотя 2-й массив

+0

Будьте любезны, если вы объяснили код немного лучше ..../что это или не делает. –

+0

Мой код работает в соседнем графстве, скажем, если бы я хотел переместить войска из Кента в Лондон, это работает, но если я хочу переместить войска из Кента в Бакингемшир (с игроком, владеющим Лондоном), он не связывает связь между переходя из Кента в Лондон, а затем бакингемшир и возвращает ложь. – user6878266

+0

Ya Я получаю суть этой части, но не то, как вы пытаетесь ее реализовать. Объясните, как это применимо к вашей таблице данных AdjcentCounties и какому scapegoat ... –

ответ

0

Если я правильно понимаю ваши требования использовать Recursion

Однако, вы также необходимо отслеживать, какие графства пути вы испробовали уже или вы могли бы попасть в бесконечный цикл ..

Private AdjcentCounties(,) As Button = New Button(,) {{Derbyshire, West_Yorkshire, South_Yorkshire, Nottinghamshire, Leicestershire, Warwickshire, Staffordshire, Cheshire, Manchester}, {Buckinhamshire, Hertfordshire, London, Berkshire, Oxfordshire, Northamptonshire, Bedfordshire, Scapegoat, Scapegoat}, {Hertfordshire, Cambridgeshire, Essex, London, Buckinhamshire, Bedfordshire, Scapegoat, Scapegoat, Scapegoat}, {Bedfordshire, Cambridgeshire, Hertfordshire, Buckinhamshire, Northamptonshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cambridgeshire, Lincolnshire, Norfolk, Suffolk, Essex, Hertfordshire, Bedfordshire, Northamptonshire, Scapegoat}, {Northamptonshire, Cambridgeshire, Bedfordshire, Buckinhamshire, Oxfordshire, Warwickshire, Leicestershire, Scapegoat, Scapegoat}, {Herefordshire, Gloucestershire, Worcestershire, Shropshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Worcestershire, Warwickshire, Gloucestershire, Herefordshire, Shropshire, Staffordshire, Scapegoat, Scapegoat, Scapegoat}, {Warwickshire, Northamptonshire, Leicestershire, Oxfordshire, Gloucestershire, Worcestershire, Staffordshire, Derbyshire, Scapegoat}, {Shropshire, Cheshire, Staffordshire, Worcestershire, Herefordshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Staffordshire, Cheshire, Derbyshire, Warwickshire, Worcestershire, Shropshire, Scapegoat, Scapegoat, Scapegoat}, {Leicestershire, Nottinghamshire, Lincolnshire, Northamptonshire, Warwickshire, Derbyshire, Scapegoat, Scapegoat, Scapegoat}, {Lincolnshire, East_Yorkshire, South_Yorkshire, Nottinghamshire, Leicestershire, Cambridgeshire, Norfolk, Scapegoat, Scapegoat}, {Nottinghamshire, Lincolnshire, Leicestershire, Derbyshire, South_Yorkshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cheshire, Merseyside, Manchester, Derbyshire, Staffordshire, Shropshire, Scapegoat, Scapegoat, Scapegoat}, {South_Yorkshire, North_Yorkshire, East_Yorkshire, Lincolnshire, Nottinghamshire, Derbyshire, West_Yorkshire, Scapegoat, Scapegoat}, {Merseyside, Lancashire, Manchester, Cheshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Manchester, West_Yorkshire, Derbyshire, Cheshire, Merseyside, Lancashire, Scapegoat, Scapegoat, Scapegoat}, {West_Yorkshire, North_Yorkshire, South_Yorkshire, Derbyshire, Manchester, Lancashire, Scapegoat, Scapegoat, Scapegoat}, {East_Yorkshire, North_Yorkshire, Lincolnshire, South_Yorkshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {North_Yorkshire, County_Durham, East_Yorkshire, South_Yorkshire, West_Yorkshire, Lancashire, Cumbria, Scapegoat, Scapegoat}, {Lancashire, Cumbria, North_Yorkshire, West_Yorkshire, Manchester, Merseyside, Scapegoat, Scapegoat, Scapegoat}, {Cumbria, Northumberland, County_Durham, North_Yorkshire, Lancashire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {County_Durham, Northumberland, North_Yorkshire, Cumbria, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Northumberland, Cumbria, County_Durham, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Cornwall, Devon, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Devon, Cornwall, Somerset, Dorset, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Somerset, Devon, Dorset, Whiltshire, Gloucestershire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Dorset, Devon, Somerset, Whiltshire, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Hampshire, Dorset, Whiltshire, Berkshire, Surrey, West_Sussex, Isle_Of_White, Scapegoat, Scapegoat}, {Isle_Of_White, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Whiltshire, Somerset, Dorset, Hampshire, Berkshire, Gloucestershire, Oxfordshire, Scapegoat, Scapegoat}, {Gloucestershire, Herefordshire, Worcestershire, Warwickshire, Oxfordshire, Whiltshire, Somerset, Scapegoat, Scapegoat}, {West_Sussex, Surrey, East_Sussex, Kent, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {East_Sussex, West_Sussex, Kent, Surrey, Hampshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Kent, East_Sussex, Surrey, London, Essex, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {London, Surrey, Berkshire, Buckinhamshire, Hertfordshire, Essex, Kent, Scapegoat, Scapegoat}, {Essex, Kent, London, Hertfordshire, Cambridgeshire, Suffolk, Scapegoat, Scapegoat, Scapegoat}, {Suffolk, Essex, Cambridgeshire, Norfolk, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Norfolk, Suffolk, Cambridgeshire, Lincolnshire, Scapegoat, Scapegoat, Scapegoat, Scapegoat, Scapegoat}, {Surrey, Kent, West_Sussex, Hampshire, Berkshire, London, Scapegoat, Scapegoat, Scapegoat}, {Berkshire, London, Surrey, Hampshire, Whiltshire, Oxfordshire, Buckinhamshire, Scapegoat, Scapegoat}, {Oxfordshire, Berkshire, Whiltshire, Gloucestershire, Warwickshire, Northamptonshire, Buckinhamshire, Scapegoat, Scapegoat}} 
Private TriedCounties As New List(Of String) 

Public Function Seeing_Connected_Counties(To_Button As Button, Initial_Button As Button, Optional Recursion As Boolean = False) As Boolean 

    If Not Recursion Then TriedCounties.Clear() ',use a list to ensure we don't try a county twice and get into an infinite loop 
    TriedCounties.Add(Initial_Button.Name) 

    Dim N As Integer = 1 
    Dim N_button As Button = Initial_Button 
    Dim T_button As Button 
    For I As Integer = 0 To UBound(AdjcentCounties, 1) 
     If N_button Is AdjcentCounties(I, 0) Then 

      'First Pass, see if destination is in list 

      For f As Integer = 0 To UBound(AdjcentCounties, 2) 
       T_button = AdjcentCounties(I, f) 
       If T_button Is To_Button Then 
        Return T_button.BackColor = To_Button.BackColor 
       End If 
      Next 

      'Second Pass, check alternate paths 

      For f As Integer = 0 To UBound(AdjcentCounties, 2) 
       T_button = AdjcentCounties(I, f) 
       If T_button IsNot ScapeGoat AndAlso T_button.BackColor = To_Button.BackColor Andalso Not TriedCounties.Contains(T_button.Name) Then 
        If Seeing_Connected_Counties(To_Button, T_button, True) Then Return True 
       End If 
      Next 
      Return False 
     Else 
    Next 
    Return False 
End Function 

Если бы это было мне, хотя, я бы переместить AdjacentCounties из рутины и сделать его класс (формы), как показано.

+0

По какой-то причине, когда я делаю AdjcentCounties переменной класса, она возвращает только «ничего»? – user6878266

+0

Возможно, вам нужно инициализировать его где-то, возможно, в функции загрузки. Я предполагаю, что это никогда не изменится. –

+0

Кстати, с этим ответом вы можете сменить ScapeGoat на Nothing и попробовать вместо этого. –

1

Возможно, вы захотите рассмотреть объектно-ориентированный подход, когда логика Business/Game/Program отделена от пользовательского интерфейса. Используя классы для представления различных свойств каждого из них, одна из них может быть, какие территории смежны и с небольшой работой, независимо от того, являются ли они дружественными или нет.

Public Class Territory 
    Public Property Name As String 
    Public Property Owner As String 
    Public Property Troops As Int32 

    Public Property AdjacentTerritories As List(Of String) 

    ' map of all the territory names 
    Public Shared TerritoryMap As String()() = { 
        New String() {"Derbyshire", "WestYorkshire", "SouthYorkshire", "Nottinghamshire", "Leicestershire", "Warwickshire", "Staffordshire", "Cheshire", "Manchester"}, 
        New String() {"Buckinhamshire", "Hertfordshire", "London", "Berkshire", "Oxfordshire", "Northamptonshire", "Bedfordshire"}, 
        New String() {"Hertfordshire", "Cambridgeshire", "Essex", "London", "Buckinhamshire", "Bedfordshire"}, 
        New String() {"Bedfordshire", "Cambridgeshire", "Hertfordshire", "Buckinhamshire", "Northamptonshire"}, 
        New String() {"Cambridgeshire", "Lincolnshire", "Norfolk", "Suffolk", "Essex", "Hertfordshire", "Bedfordshire", "Northamptonshire"}, 
        New String() {"Northamptonshire", "Cambridgeshire", "Bedfordshire", "Buckinhamshire", "Oxfordshire", "Warwickshire", "Leicestershire"}, 
       ... you get the idea 

    Public Sub New(n As String) 
     Name = n 

     Dim tmp = TerritoryMap. 
         Where(Function(t) t(0) = n). 
         SelectMany(Function(k) k). 
         ToArray() 

     AdjacentTerritories = New List(Of String)(tmp.Skip(1). 
           Take(tmp.Length - 1)) 
    End Sub 

    Public Function IsAdjacentTo(otherShire As String) As Boolean 
     Return AdjacentTerritories.Contains(otherShire) 
    End Function 

End Class 

На карте территория неровный массив так, что все «козла отпущения» заполнители не должны существовать. Код использует имя в каждой «строке» в качестве имени локальной территории. Поэтому при создании списка первый пропущен.

Обратите внимание, что смайлики для прилегающих территорий: инкапсулированные. Поскольку территории не перемещаются в ходе игры, хранение списка из них предотвращает любую потребность в цикле, повторении, анализе или любых других циклах.

Механизм создания всех территорий, использует «карта», а также:

' main list of territories 
Dim TerrList As New List(Of Territory) 

' extract the first element from each row for iterating 
Dim terrTmp = Territory.TerritoryMap.Select(Function(j) j(0)).ToArray() 

For Each tName In terrTmp 
    TerrList.Add(New Territory(tName)) 
Next 

Не так много к нему и каждый из «знает», кто их соседи:

For Each t As Territory In TerrList 
    Console.WriteLine("Here in {0}, our neighbors are:", t.Name) 
    Console.WriteLine(String.Join(", ", t.AdjacentTerritories)) 
Next 

Результат (частичное):

Здесь в Buckinhamshire, наши соседи:
Хартфордшир, Лонд на, Беркшир, Оксфордшир, Нортгемптоншир, Бедфордшир
Здесь в Хартфордшир, наши соседи:
Кембриджшир, Эссекс, Лондон, Buckinhamshire, Бедфордшир
Здесь в Бедфордшир, наши соседи:
Кембриджшир, Хартфордшир, Buckinhamshire, Нортгемптоншир

Обычно вы будете проверять одно имя (пока вы не сделаете поиска пути):

Dim rndTerr1 = TerrList.RandomItem() 
Dim rndTerr2 = TerrList.RandomItem() 

If rndTerr1.IsAdjacentTo(rndTerr2.Name) Then 
    Console.WriteLine("Attack {0} from {1}!!!", rndTerr1.Name, rndTerr2.Name) 
Else 
    Console.WriteLine("{0} cannot attack {1}....YET!", rndTerr1.Name, rndTerr2.Name) 
End If 

Это грубый из Безразлично» t включать, кто владеет каждой территорией. Для этого потребуется доступ к списку основных территорий или AdjacentTerritories в качестве List(Of Territory).