Tuesday 28 January 2014

How did you implement a shooting algorithm for the game of Battleship?

Let me describe it a little bit. I took a course on Java programming at my university. I had to implement the game of Battleship in the framework of my project.

The application was divided into 3 parts: model, controller and view (traditional MVC). You could play the game in console using only the model part. The model package (module) contained the main class Model. The Model class contained two attributes of type Player (two players: fist and second) and shotPlayer attribute that denoted the player who could shoot (of type PlayerState). When a shot arrived, the PlayerState object routed the shot to the player that was shot. For example, if first player shot, the PlayerState object routed the shot to the second player.

The PlayerModel class contained the "opponentHit(Point point)" method. Point had two attributes: (x,y) coordinates of the shot. In the method, the shot was sent to the player's board called Sea. The Sea board consisted of fields. Each field had a state:

    /** Field is not used. */
    UNUSED,
    /** Field has been hit and it was a miss. */
    MISS,
    /** There is a mast and the field has not been hit yet. */
    SHIP,
    /** There was a mast, but the field has been hit. */
    HIT,
    /** There was a mast and the ship (which contained the mast) was sunk. */
    DESTROYED

Each stated of the field decided on the transition to the next state and the new state was returned. I used the state design pattern here. The coordinates of the point determined the field of the Sea. If the previous state of the field was UNUSED then there was a miss. If the previous state of the field was SHIP then there was a hit. Otherwise, the shot should be repeated.

The code can be found here: https://github.com/adam-dziedzic/battleShips