Time for action - GamePiece class methods part 3 connection methods

  1. Add the GetOtherEnds() method to the GamePiece class:
    public string[] GetOtherEnds(string startingEnd)
    {
    List<string> opposites = new List<string>();
    foreach (string end in pieceType.Split(','))
    {
    if (end != startingEnd)
    opposites.Add(end);
    }
    return opposites.ToArray();
    }
    
  2. Add the HasConnector() method to the GamePiece class:
    public bool HasConnector(string direction)
    {
    return pieceType.Contains(direction);
    }
    

The GetOtherEnds() method creates an empty List object for holding the ends we want to return to the calling code. It then uses the Split() method of the string class to get each end listed in the pieceType. For example, the Top,Bottom piece will return an array with two elements. The first element will contain Top and the second will contain Bottom. The comma delimiter will not be returned with either string.

If the end in question is not the same as the startingEnd parameter that was passed to the method, it is added to the list. After all of the items in the string have been examined, the list is converted to an array and returned to the calling code.

In the previous example, requesting GetOtherEnds("Top") from a GamePiece with a pieceType value of Top,Bottom will return a string array with a single element containing Bottom.

We will need this information in a few moments when we have to figure out which pipes are filled with water and which are empty.

The second function, HasConnector() simply returns "true" if the pieceType string contains the string value passed in as the direction parameter. This will allow code outside the GamePiece class to determine if the piece has a connector facing in any particular direction.

Sprite sheet coordinates

Because we set up the PieceTypes array listing the pieces in the same order that they exist on the sprite sheet texture, we can calculate the position of the rectangle to draw from based on the pieceType.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.207.129