XNA 4.0 Game Development by Example: Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – making the connection

  1. Add the PropagateWater() method to the GameBoard class:
      public void PropagateWater(int x, int y, string fromDirection)
      {
          if ((y >= 0) && (y < GameBoardHeight) &&
              (x >= 0) && (x < GameBoardWidth))
          {
              if (boardSquares[x,y].HasConnector(fromDirection) &&
                  !boardSquares[x,y].Suffix.Contains("W"))
              {
                  FillPiece(x, y);
                  WaterTracker.Add(new Vector2(x, y));
                  foreach (string end in
                           boardSquares[x,y].GetOtherEnds(fromDirection))
                      switch (end)
                            {
                          case "Left": PropagateWater(x - 1, y, "Right");
                              break;
                          case "Right": PropagateWater(x + 1, y, "Left");
                              break;
                          case "Top": PropagateWater(x, y - 1, "Bottom");
                              break;
                          case "Bottom": PropagateWater(x, y + 1, "Top");
                              break;
                      }
              }
          }
      }
  2. Add the GetWaterChain() method to the GameBoard class:
      public List<Vector2> GetWaterChain(int y)
      {
          WaterTracker.Clear();
          PropagateWater(0, y, "Left");
          return WaterTracker;
      }
    

What just happened?

Together, GetWaterChain() and PropagateWater() are the keys to the entire Flood Control game, so understanding how they work is vital. When the game code wants to know if the player has completed a scoring row, it will call the GetWaterChain() method once for each row on the game board:

What just happened?

The WaterTracker list is cleared and GetWaterChain() calls PropagateWater() for the first square in the row, indicating that the water is coming from the Left direction.

The PropagateWater() method checks to make sure that the x and y coordinates passed to it exist within the board and, if they do, checks to see if the piece at that location has a connector matching the fromDirection parameter and that the piece is not already filled with water. If all of these conditions are met, that piece gets filled with water and added to the WaterTracker list.

Finally, PropagateWater() gets a list of all other directions that the piece contains (in other words, all directions the piece contains that do not match fromDirection). For each of these directions PropagateWater() recursively calls itself, passing in the new x and y location as well as the direction the water is coming from.