Drawing the shot on the grid

Add the highlighted code to the draw method as shown next. Note I have not shown the entire draw method because it is getting quite long but there should be sufficient context to allow you to add the newly added highlighted code in the correct place.

// Draw the horizontal lines of the grid
for(int i = 0; i < gridHeight; i++){
   canvas.drawLine(0, blockSize * i,
   numberHorizontalPixels, blockSize * i,
   paint);
}

// Draw the player's shot
canvas.drawRect(horizontalTouched * blockSize, 
 verticalTouched * blockSize,
 (horizontalTouched * blockSize) + blockSize,
 (verticalTouched * blockSize)+ blockSize,
 paint );

// Re-size the text appropriate for the
// score and distance text
paint.setTextSize(blockSize * 2);
paint.setColor(Color.argb(255, 0, 0, 255));
canvas.drawText(
   "Shots Taken: " + shotsTaken +
   "  Distance: " + distanceFromSub,
   blockSize, blockSize * 1.75f,
   paint);

The code we just added draws a square in the appropriate grid position. The key to understanding the slightly lengthy single line of code is to restate what each argument of the drawRect method does. Let's break it down from left to right.

  1. The left horizontalTouched * blockSize
  2. The top verticalTouched * blockSize
  3. The right (horizontalTouched * blockSize) + blockSize
  4. The bottom verticalTouched * blockSize)+ blockSize
  5. Our Paint instance, paint

See how we use a simple calculation on the key variables horizontalTouched, verticalTouched and blockSize to arrive at the correct place to draw the square. This works because horizontalTouched and verticalTouched were cast to int and multiplied by blockSize in the takeShot method previously. Here is a reminder of that fact.

horizontalTouched = (int)touchX/ blockSize;
verticalTouched = (int)touchY/ blockSize;

As the absolute last thing, still inside the draw method at the very end, change the call to printDebuggingText by wrapping it in an if statement that will cause the debugging text to be drawn when debugging is set to true but otherwise not.

if (debugging) {
   printDebuggingText();
}

The Sub' Hunter game is complete!