- XNA 4.0 Game Development by Example Beginner's Guide(Visual Basic Edition)
- Kurt Jaegers
- 484字
- 2021-08-20 15:50:40
Time for action – Game1 declarations
- Double click on the
Game1.vb
file in Solution Explorer to reactivate theGame1.vb
code file window. - Add the following declarations to the
Game1
class member declaration area:Private _gameBoard As GameBoard Private gameBoardDisplayOrigin As New Vector2(70, 89) Private playerScore As Integer = 0 Private Enum GameStates TitleScreen Playing End Enum Private gameState As GameStates = GameStates.TitleScreen Private EmptyPiece As Rectangle = New Rectangle(1, 247, 40, 40) Private Const MinTimeSinceLastInput As Single = 0.25 Private timeSinceLastInput As Single = 0
What just happened?
The _gameBoard
instance of GameBoard
will hold all of the playing pieces, while the gameBoardDisplayOrigin
vector points to where on the screen the board will be drawn. Using a vector like this makes it easy to move the board in the event that you wish to change the layout of our game screen.
As we did in SquareChase
, we store the player's score and will display it in the window title bar.
In order to implement a simple game state mechanism, we define two game states. When in the TitleScreen
state, the game's title image will be displayed and the game will wait until the user presses the Space bar to start the game. The state will then switch to Playing
, which will display the game board and allow the user to play.
Tip
Enumerations (Enums)
An Enum, or enumeration, is a list of named values that we are using to build a custom type. Variables of this type can then be declared and assigned any of the values from the enumerator list. Using an enumerator instead of, say, assigning numbers to each state (that is, 1
is at the Title
Screen
, 2
is Playing
) allows you to keep your code more readable. It also provides some basic error detection, because you will get a compiler error if you try to assign a value not on the enumerator list to the variable.
If you look at the sprite sheet for the game, the pipe images themselves do not cover the entire 40x40
pixel area of a game square. In order to provide a background, an empty tile image will be drawn in each square first. The EmptyPiece
rectangle is a convenient pointer to where the empty background is located on the sprite sheet.
Just as we used an accumulating timer in SquareChase
to determine how long to leave a square in place before moving it to a new location, we will use the same timing mechanism to make sure that a single-click by the user does not send a game piece spinning unpredictably. Remember that the Update()
method will be executing up to 60
-times-each-second, so slowing the pace of user input is necessary to make the game respond in a way that feels natural.
Initialization
Before we can use the _gameBoard
instance, it needs to be initialized. We will also need to enable the mouse cursor.