Board game pawn movement algorithm
Try creating a recursive method.
List<Spot> CheckMoves(Spot curSpot, int remainingMoves, List<Spot> moveHistory){ List<Spot> retMoves = new List<Spot>(); if( remainingMoves == 0 ) { retMoves.Add(curSpot); return retMoves; } else { moveHistory.Add(curSpot); if( !moveHistory.Contains(Spot.North) ) { retMoves.AddRange( CheckMoves( Spot.North, remainingMoves - 1, moveHistory ); } /* Repeat for E, W, S */ }}
This will return a List (where spot is the class that represents a position on the board) that contains all potential final positions. Of course you'll need to be a bit more thorough in making sure the Spot.North is a valid spot, but this is a basic idea for you.
The method above won't allow the user to move into the same spot twice in a single move, but doesn't look for barricades or other obstructions. It also doesn't handle any spots which halt movement or have no possible movement in a particular direction.
It should, however, give you an idea of how it should go.
Something like this should do it,
It recusively enumerates each link and adds the Field
s to a HashSet
to prevent duplicates. The recursion stops when, the worp
counts down to 0
, the link is null
or a barrier pawn
is located.
public IList<Field> GetPossibleMoves(int worp){ var valid = new HashSet<Field>(); foreach (var f in GetPossibleMoves(current.LinkNorth, worp)) { valid.Add(f); } foreach (var f in GetPossibleMoves(current.LinkEast, worp)) { valid.Add(f); } foreach (var f in GetPossibleMoves(current.LinkSouth, worp)) { valid.Add(f); } foreach (var f in GetPossibleMoves(current.LinkWest, worp)) { valid.Add(f); } return valid.ToList();}private static IEnumerable<Field> GetPossibleMoves(Field current, int worp){ if (current == null) { yield break; } yield return current; if (worp == 0 || current.BarricadePawn) // is that a bool? { yield break; } foreach (var f in GetPossibleMoves(current.LinkNorth, nextWorp)) { yield return f; } foreach (var f in GetPossibleMoves(current.LinkEast, nextWorp)) { yield return f; } foreach (var f in GetPossibleMoves(current.LinkSouth, nextWorp)) { yield return f; } foreach (var f in GetPossibleMoves(current.LinkWest, nextWorp)) { yield return f; }}
It could be optimised by omitting the calculation of backward moves which would prevent a lot of Add
s being discarded from the HashSet
.