Learning Java by Building Android  Games
上QQ阅读APP看书,第一时间看更新

Planning the variables

Let's have a think about what our game needs to keep track of. This will dictate the variables, types, and names that we will declare.

  • We need to know how many pixels wide and high the screen is comprised of. We will call these variables numberHorizontalPixels and numberVerticalPixels. They will be of type int.
  • Once we have calculated the size (in pixels) of one block on the game grid we will want to remember it. We will use an int variable called blockSize.
  • If we have the size of each block we will also need to know the number of blocks both horizontal and vertical that fit on a given screen/grid. We will use variables named gridWidth and gridHeight which will also be of type int.
  • When the player touches the screen, we will need to remember and use the coordinates that were touched. These values will be precise floating-point coordinates and we will name them horizontalTouched and verticalTouched.
  • It will also be necessary to choose and remember which grid position (horizontally and vertically) the sub' is randomly spawned in. Let's call them subHorizontalPosition and subVerticalPosition. These will also be of type int.
  • Each time that the player takes a shot we will need to know whether the sub was hit- or not. This implies a boolean variable and we will call it hit.
  • The shotsTaken variable will be of type int and as the name implies will be used to count the number of shots the player has had so far.
  • The distanceFromSub will be used to store the calculated distance of the player's most recent shot from the sub'. It will be an int type variable.
  • Finally, before we fire up Android Studio, we will need to know whether we want to output all the debugging text or just show the actual game. A boolean named debugging will do nicely.

Now we know the names and types of all the variables that will be in our game we can declare them, so they are ready for use as we need them.