Technical Description

Our program was laid out into 4 separate sections, Setup, Board Display, Game Logic and Computer Logic. These parts all have connections in their input or output or just in whether they use each other. For example, Setup creates a final matrix with the ship locations from the user which is then used in Game Logic and Board Display.

 

Setup

The setup section prompts the user to place all of their ships. This involves the direction of the ship and its top-most coordinate. This section then places the ships into a matrix for Board Display to use. There is also a level of input sanitation for the direction and coordinate, as users cannot overlap ships or let ships go out of the bounds of the 10×10 board.

This section also takes care of the computer’s random ship placement from the instructor provided Setup function (which is different from this section). It will parse the output matrix and place it in the correct locations

Setup is located from Line 1 to 295.

Board Display

The board display section handles displaying both of boards and aligning them one on top of the other. It also has code for loading the Battleship.mat file, which contains the pictures and matrices for the Opponent and Player boards. The logic has the ability to determine what direction the ship goes in, whether the image must be a ship center and whether the location is just water.

Game Logic

The game logic section handles all of the code for looping the game. This includes prompting the player and computer every turn and changing the boards to reflect the choices made. There are also sounds played after each action, like an explosion after a hit or a ship sinking after we sink a ship. There are also message boxes and error boxes after each turn for displaying to the player what occurred last turn.

The game ends when the board has no ships left, or when the ship location matrix is made of only 0s. This is determined at the end of the loop and sets a variable that will be 0 when the game is over or 1 when the game is still going.

Computer Logic

The computer logic handles outputting the x and y coordinates for the AI’s decision every turn. The code is created as a function, is housed in the computerTurn.m file and is used by calling [x,y] = computerTurn(vars…).

The logic starts off by determining if the last shot was a hit to determine what happens next. If the last shot was not a hit, it should randomly find another coordinate. If the last shot was a hit, then it needs to determine if the last shot was a new consecutive shot or not. If it was a brand new hit, then this means that the computer just found a ship and is going to find it’s direction then follow it up and down or left and right till it sinks it. The remaining logic just determines where the last shot was in relation to the initial hit, and uses this to find if it needs to finish sinking the ship or not.