Battleship

Description

Battleship is a JavaScript game I created using Test-Driven Development. It implements a graph data structure comprised of nodes (vertices) and edges which form the board.

Viewing the layout of your ships. 'Reset' will reset the game and shuffle the layout.
'View' will switch to the enemies' board.

Objective

The objective was to create a classic game of Battleship using Jest for TDD and a graph data structure to layout the board.
The computer controlled opponent would need it's own playstyle and logic. It couldn't be too difficult, so an element of randomness needed to be implemented to humanize it's moves.

Scoring a hit on an enemy ship! 💥

Tech used

JavaScript initialized a Gameboard class with 100 nodes and 5 ships, each node referencing adjacent neighbors. The game was first made playable in the console before adding a graphical interface.


Making the game console-playable required extensive Jest test cases to ensure hits were accurate and ships didn't overhang the play area. Writing tests first and then fulfilling them built confidence and saved debugging time.

Small touches like animated tiles and CSS screen shakes make the game more immersive

Challenges

Placement of ships was quite challenging. It involved working out whether a node was a valid/open position, and also had to check ahead multiple nodes in the case of longer ships to make sure they were valid positions too.

Another difficulty was adjusting the computer opponent to be challenging, but not unbeatable or a complete pushover.
Originally, I went down the path of getting it to try guess ahead attack positions based off multiple previously hit positions. This proved overly complex and ultimately unnecessary.
In the end I made it do a handful of actions based on chance:
Attack randomly, attack an adjacent node to the last one hit, or simply land a direct hit on a previously hit ship.
Whilst the last action seems counterintuitive and unfair at first, it only starts to happen the longer the game goes on. In this way, the difficulty could be adjusted and the player experience remained good.

The computer had to operate in different modes. Seek ships with random shots. If a ship was hit, switch into kill mode and try finish off the ship that was hit.

Let's Keep in Touch

If you're after a developer for your next project, have something you'd like to ask or just want to stay in touch, feel free to reach out.

ruuksine@gmail.com