Placing Battleships [beginners exercise]

This is where most of us started. Classic Spectrum basic.

Moderator: Programming Moderators

Post Reply
User avatar
Posts: 14
Joined: Thu Jun 01, 2017 7:15 pm

Placing Battleships [beginners exercise]

Post by Brayn-3 » Thu Jul 20, 2017 2:59 pm

Like in the beginning of the game Battleship we want to place ships. The ships must not lie on top of each other or touch other ships (not even diagonal). Instead of a 10x10 field we take a bigger 100x100 field and place 500 ships. The ships should have lengths between 2 and 6.

Please wait to post your solutions until the challenge has ended. But you can post a picture or ask any questions (also via pm).

Have fun! :-)

Facebook discussion
Battleships2.png (2.68 KiB) Viewed 1177 times
Battleships1.png (5.53 KiB) Viewed 1177 times
Description of the algorithm

At first we initialize the variables n, max, fldX, fldY, fldW, and fldH (see the Nassi–Shneiderman diagram). Then we draw a frame around the field by leaving a gap of one pixel (so the field including the frame is 104 pixels wide and high).

Now we begin with the placing loop (marked with # in the diagram). A random length L is chosen between 2 and 6 and the variable h is set to a random number 0 (=vertical) or 1 (=horizontal). Depending on if the ship is horizontal or not, we branch to one of two very similar program parts.

First a random postion (x,y) is set (under consideration of the ship's length). All ship and surrounding positions are tested for vacancy in two nested loops. If one of the points (i,j) is set, then the vacancy v is set to false (=0) and the loop will be exited by jumping to #. (This is normally not allowed in structured programming, but it is simpler here.). If all points are tested (not set), then the line for the ship will be drawn.

At the end of the main loop the counter n will be increased and while n is less than max, the loop repeats at #.

EDIT: The algorithm in following diagramm does not jump back to #. it jumps behind the loops and tests v, if the line has to be drawn.
Battleships-NSDv2.png (67.83 KiB) Viewed 1142 times

Post Reply