Battleship 2 – Improving shots
So, what did I need to change? The main change is the part where the players press buttons A and B to select the fire_x and fire_y coordinates. Remember that pressing both buttons fired a shot at those coordinates.
To see the fire_x and fire_y on the screen and decide where to fire a shot at, we need to:
Clear the screen of our ships
Light up the LED at (fire_x, fire_y)
As buttons A and B are pressed, update (fire_x, fire_y) and light up the LED at that location
When buttons A and B are pressed together, fire a shot and bring back our original battlefield with our ships
The following code piece does exactly that:
Note the use of “plot-unplot-plot” (fire_x,fire_y) to show the change in the coordinates as we press buttons A and B separately.
Pressing both buttons together brings back ours ships using the function showShips.
What does this function look like? This function needs to go over the “my_battle_area” array and check which elements are equal to 1. Then, it calculates the location of the corresponding LED from the index of those elements and lights this LED up.
Note that since the for loop starts from 0, we are making some unnecessary checks for the first row, which does not have any ships. To avoid this, we may choose to keep a smaller array that matches the battle area (4×5 matrix with 20 elements instead of 5×5 matrix with 25 elements). But then, we would need to change the calculation of the coordinates to light up the correct LEDs. Finally, functions are more useful when they represent a code piece called repeatedly from different places in the code. In this program, this is not the case. However, it helps with improving readability of our code through meaningful abstractions. This is why I also added a pickShips function to “On Start”. The final code is below.