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

Time for action – GamePiece class methods – part 2 – rotation

  1. Add the RotatePiece() method to the GamePiece class:
      public void RotatePiece(bool Clockwise)
      {
          switch (pieceType)
          {
              case "Left,Right":
                  pieceType = "Top,Bottom";
                  break;
              case "Top,Bottom":
                  pieceType = "Left,Right";
                  break;
              case "Left,Top":
                  if (Clockwise)
                      pieceType = "Top,Right";
                  else
                      pieceType = "Bottom,Left";
                  break;
              case "Top,Right":
                  if (Clockwise)
                      pieceType = "Right,Bottom";
                  else
                      pieceType = "Left,Top";
                  break;
              case "Right,Bottom":
                  if (Clockwise)
                      pieceType = "Bottom,Left";
                  else
                      pieceType = "Top,Right";
                  break;
              case "Bottom,Left":
                  if (Clockwise)
                      pieceType = "Left,Top";
                  else
                      pieceType = "Right,Bottom";
                  break;
              case "Empty":
                  break;
          }
      }

What just happened?

The only information the RotatePiece() method needs is a rotation direction. For straight pieces, rotation direction doesn't matter (a left/right piece will always become a top/bottom piece and vice versa).

For angled pieces, the piece type is updated based on the rotation direction and the diagram above.

Tip

Why all the strings?

It would certainly be reasonable to create constants that represent the various piece positions instead of fully spelling out things like Bottom,Left as strings. However, because the Flood Control game is not taxing on the system, the additional processing time required for string manipulation will not impact the game negatively and helps clarify how the logic works.

Pipe connectors

Our GamePiece class will need to be able to provide information about the connectors it contains (Top, Bottom, Left, and Right) to the rest of the game. Since we have represented the piece types as simple strings, a string comparison will determine what connectors the piece contains.