官术网_书友最值得收藏!

Time for action – initializing the game board

  1. Add a constructor to the GameBoard class:
    Public Sub New(pieceTexture As Texture2D, emptyArea As Rectangle)
      playingPieces = pieceTexture
      emptyPiece = emptyArea
      ClearBoard()
    End Sub
  2. Add the ClearBoard() helper method to the GameBoard class:
    Public Sub ClearBoard()
      Dim x, y As Integer
      For x = 0 To GameBoardWidth
        For y = 0 To GameBoardHeight
          boardSquares(x, y) = New GamePiece("Empty")
        Next
      Next
    End Sub

What just happened?

When a new instance of the GameBoard class is created, we store the texture and rectangle values that we will need for drawing, and the constructor calls the ClearBoard() helper method, which simply creates 80 empty game pieces and assigns them to each element in the array.

Tip

Helper methods

Why not simply put the two for loops that clear the board into the GameBoard constructor? Splitting work up into methods that accomplish a single purpose greatly helps to keep your code both readable and maintainable. Additionally, by splitting ClearBoard() out as its own method, we can call it separately from the constructor. When we add increasing difficulty levels in Chapter 3, Flood Control - Smoothing Out the Rough Edges, we will make use of this call when a new level starts.

Updating GamePieces

The boardSquares array in the GameBoard class is declared as a private member, meaning that code that uses the GameBoard will not have direct access to the pieces contained on the board.

In order for code in our Game1 class to interact with a GamePiece, we will need to create public methods in the GameBoard class that expose the pieces in boardSquares.

主站蜘蛛池模板: 麻栗坡县| 吉首市| 葫芦岛市| 丹寨县| 米脂县| 犍为县| 福建省| 全南县| 东丰县| 阿勒泰市| 曲水县| 永宁县| 崇阳县| 右玉县| 莎车县| 遂溪县| 英吉沙县| 普安县| 安阳县| 阜宁县| 富川| 莱阳市| 酒泉市| 永春县| 酒泉市| 朔州市| 潞西市| 庆安县| 漳浦县| 根河市| 犍为县| 广东省| 蒙自县| 内江市| 邵阳市| 江源县| 万荣县| 乌鲁木齐市| 绩溪县| 惠安县| 山西省|