Search
  • Cigdem Sengul

Battleship 2 – Improving shots

In the previous post, I aimed to show a simple solution for the  Battleship game. I ended the post mentioning that several improvements are possible.  I suggested showing the selection of fire_x and fire_y on the micro:bit screen. This way players can see which position they select for firing a shot.  In this post, I describe an implementation of this.  I use the new “Functions” block under “Advanced” tab in the JavaScript Blocks Editor. This was a first for me too! 

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:


  1. Clear the screen of our ships

  2. Light up the LED at (fire_x, fire_y)

  3. As buttons A and B are pressed, update (fire_x, fire_y) and light up the LED at that location

  4. 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.


0 views0 comments

Recent Posts

See All