Battleship game in Java: How to program

How to make a Battleship game in Java. Commented and explained code in step-to-step for Java beginnersNow, that we already learned how to pass arrays (of any size) for methods, we can do something more useful. Let's do the famous game called naval battle, in text mode.

We use everything we have learned so far in our Java course: if else, while loop, loop, methods, random numbers, arrays, multidimensional arrays and creativity.

Rules of Battleship in Java Game

There is a 5x5 board, ie 25 blocks. There are 3 hidden ships (one in each block).
The objective of the game is figuring out where these ships are placed and hit them.
Every shot fired is said if you hit a ship. If you have wrong is told how many ships are in that row and that column.
The game only ends when you find and sink the 3 ships.

Legend pro user:
~: Water in the block. Still not been shot.
*: Shot fired, there's nothing there.
X: shot fired, there was a ship.

How to play Battleship in Java Game:

Each round, enter two numbers: the number of the row and column number where you want to give the shot.
Then just wait to see if hit some ship, or the hint.

To Java programmers:

The board is 5x5 integer. It is initialized with values ​​'-1'.
Every shot, it is upgraded, depending on whether you hit or missed. These figures serve to show '~', '*' or 'X' for the user.
Also serve to display tooltips.

Labels of the board:

 -1: No shot was given in that block (~)
  0: the shot was given and there was no ship there (*)
  1: The user shot and had a ship there (X)


  • void initBoard (int[][] board) - initially sets the value -1 in all blocks of the board
  • void showBoard (int[][] board) - gets the int matrix and shows the board game
  • void initShip (int[][] ships) - this method randomly select 3 pairs of integers numbers, which are the location of the 3 ships
  • void shoot (int[] shot) - gets a shot (row and column) of the user, and stores in variable shot[]
  • boolean shotHit(int[] shot, int[][] ships) - checks if given shot hit a ship
  • void hint(int [] shot, int[][] ships, int attempt) - gives a hint of how many ships are in that row and that column where the shot was given
  • void changeBoard (int[] shot, int[][] ships, int[][] board) - after the shot is given, the board is changed, showing that the shot was given (if hit or missed)

How to make a Battleship game in Java. Commented and explained code in step-to-step for Java beginners

Understand the Battleship Java Game logic

Initially, the variables are created 'board[5][5]', which will store the game board, the variable 'ships[3][2]', which will store the position (row and column) of the 3 hidden ships on the board, the variable 'shot[2]' that will store the position (row and column) of the shot that the player will take each round, plus the variable 'attempt', which will store the number of attempts the player has to hit the 3 ships and, finally, the variable 'shotHit' that counts the number of ships you hit.

Method 'initBoard()' is triggered, to create the board with the number '-1' in all positions.

Once the method is 'initShips()', which will fill the position of 3 ships (row and column).
This method draws randomly two numbers between 0 and 4. Then it checks if this number is out because no two boats should be placed at the same position.
If it this position have already chosen, the method enter in a do ... while loop that will randomly select the numbers, and only comes out when draws another pair of numbers that is not the location of some ship.

After that, in 'main()', we start the game.
The games begin using a do ... while loop. In this case, the condition of the loop is "shotHit! = 3 '. That is, until you hit the 3 ships, the game goes on.

The first thing that occurs in the loop is to show the board, through the loop 'showBoard()'.
This method checks each position of the 'board[5][5]'.
If -1 ,it exhibits water, '~'.
If 0, it displays the shot was given and missed, '*', and if it is 1, it displays 'X' indicates that you hit a ship that position.

After showing the board, you will give your shot through the method 'shoot()', which takes two integers.
Note that the user will enter numbers from 1 to 5, because it counts from 1 to 5.
You, as a Java programmer, that counts from 0 to 4.
Therefore, after the user enters the row and column, SUBTRACT 1 of each of these value.
That is, if user has entered (1.1) in its Java board 5x5, it will represents the position (0.0).

After the shot was given, our game in Java will check if that shot hit a ship. This is done with the method 'hit()', which returns 'true' if set and 'false' case err.
In the method, it simply checks if the pair of values ​​- 'shooting[2]' - that define your shot, hit with some of the values ​​that define the position of ships - ships[3] [2].
If hit, the value of 'shotHit' increases.
Hitting or missing, 'attempts' increases, because an attempt was made.

Hitting or missing, a tip is also displayed. This tip is displayed through the method 'hint()', which will look at your 'shot[2]', and look up the row and column you tried to ship some over there, picking the 'ships[3][2] '.
Note that the row of your shot is 'shot [0]' and the column is 'shot [1]'.
The line of each ship is 'ships[x][0]' column and each ship is 'ships[x][1]', where 'x' is the number of the ship. In our case, are three ships, ie ranging from 0 to 2.

Hitting or missing, the board will be changed. The shot you took that spot will change the board, will appear as shot '*' or shot that hit 'X'.

We will do this through the method 'changeBoard()'.
Here, we use a method inside the other. Thing that we have explained in our Java course.
We checked whether the shot given 'shoot[2]' struck by the method that we have used and explained, 'hit()'.
If hit, the board position for the shot you gave will change from '-1' to '1 '.
If err, the board position for the shot you gave will change from '-1' to '0 '.
So when the board is displayed, display with '*' or 'X' in place of this ancient '~'.

import java.util.Random;
import java.util.Scanner;

public class battleShip {

    public static void main(String[] args) {
        int[][] board = new int[5][5];
        int[][] ships = new int[3][2];
        int[] shoot = new int[2];
        int attempts=0,

        System.out.println("\n\n\nBattleship Java game finished! You hit 3 ships in "+attempts+" attempts");
    public static void initBoard(int[][] board){
        for(int row=0 ; row < 5 ; row++ )
            for(int column=0 ; column < 5 ; column++ )
    public static void showBoard(int[][] board){
        System.out.println("\t1 \t2 \t3 \t4 \t5");
        for(int row=0 ; row < 5 ; row++ ){
            for(int column=0 ; column < 5 ; column++ ){
                }else if(board[row][column]==0){
                }else if(board[row][column]==1){


    public static void initShips(int[][] ships){
        Random random = new Random();
        for(int ship=0 ; ship < 3 ; ship++){
            //let's check if that shot was already tried 
            //if it was, just finish the do...while when a new pair was randomly selected
            for(int last=0 ; last < ship ; last++){
                if( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) )
                    }while( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) );

    public static void shoot(int[] shoot){
        Scanner input = new Scanner(;
        System.out.print("Row: ");
        shoot[0] = input.nextInt();
        System.out.print("Column: ");
        shoot[1] = input.nextInt();
    public static boolean hit(int[] shoot, int[][] ships){
        for(int ship=0 ; ship<ships.length ; ship++){
            if( shoot[0]==ships[ship][0] && shoot[1]==ships[ship][1]){
                System.out.printf("You hit a ship located in (%d,%d)\n",shoot[0]+1,shoot[1]+1);
                return true;
        return false;

    public static void hint(int[] shoot, int[][] ships, int attempt){
        int row=0,
        for(int line=0 ; line < ships.length ; line++){
        System.out.printf("\nHint %d: \nRow %d -> %d ships\n" +
                                 "Column %d -> %d ships\n",attempt,shoot[0]+1,row,shoot[1]+1,column);

    public static void changeboard(int[] shoot, int[][] ships, int[][] board){

It is challenging for you make a game Battleship, but human x human. 

The game is turn based. Create a variable called 'shift' that is incremented each round, and use the remainder of the division by 2 to know whose turn it is.
For example, if
turn = 1 -> turn % 2 = 1 -> first player's turn
turn = 2 -> turn % 2 = 0 -> player 2
turn = 3 -> turn % 2 = 1 -> player 1
turn = 4 -> turn % 2 = 0 -> player 2
Create two variables 'board', two 'attempts', two 'ships' and two 'hits' on different variables to store the data for each user. Or just Oriented Object programming.
The game ends when one of the variables 'hits' is 3.
Or you can change the board size, the number of ships, etc ... tip your creativity is what counts.

Programming graphics games in Java

We've done a sample game in Java using dialog boxes, just like we did the same in text mode.
You saw that, the logic is the same, and is by far the most important part.

Understanding and playing the game Battleship Java text mode, you'll know how the logic of the game is created and how it works. The graphic uses the same logic. You will simply put some visuals / graphics (GUI - Graphic User Interface) that your Java application.

Many people think that programming games is just the visuals.
But this is only one part. It is usually not difficult, is not the most important nor that takes more work.
Programming games is first programmed. Learn the language before, logic, syntax.
Then, throughout the course, you will learn to use the graphics capabilities of Java, such as menus, buttons and windows, and we will teach you how to use that same game in a graphical way, for you to send to your friends :)

For now, consider the logic and calm down.
Programming is a profession. Do not create a game or learn to program in Java in a few weeks or months. Keep studying ...


sl4x said...

Reeeeally! Cool!
Finally a code that I could understand! Very easy!

Anonymous said...

what will be the size of each ship ? 5 cells? or not

Progressive Java Tutorial said...

Just one.

it has the size of one position in matrix

Anonymous said...

where is link to full source code?
please help.

Anonymous said...

You should be able to copy the code. I think they have done a great job. Your "part" is now to select the java code, copy it, paste it in a java project, and run... :)

Anonymous said...

is there a way to increase the size of the ship?

Neo said...

Thanks bro for the post. It has helped me a lot in preparation of my interview