2 Replies - 332 Views - Last Post: 06 June 2014 - 12:48 PM Rate Topic: -----

#1 java101*  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-June 14

Why do I get these errors? Battleship-Java

Posted 06 June 2014 - 10:55 AM

Hello everybody!
I'm trying to create a simple Battleship game in Java but I'm having trouble with my 'addShip' method.
It should basically check if the coordinates are within the range of the board and if the place is empty.
If so it will place the ships.
Here's my code:
public class Sea {

	private int width;
	private int height;
	private final int[][] board;
	private boolean[][] bombField;
	public final static int WATER = 0;

	
	public Sea(int width, int height) {
		this.width = width;
		this.height = height;
		this.board = new int[width][height];
		this.bombField = new boolean[width][height];

	}
	
	
	int x;
	int y;

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	

	boolean addShip(ShipType type, Direction dir, int x, int y) {

		if ((getX() > width && getX() < 0 && getY() > height && getY() < 0)

		|| (board[getX()][getY()] != WATER) || (bombField[getX()][getY()])) {

			System.out.println("Invalid position!");

			return false;
		}

		else {

			if (dir == Direction.NORTH)
				for (int i = 0; i < type.getLength(); i++) {
					board[getX()][getY() - i] = type.getLength();
				}

			else if (dir == Direction.SOUTH)
				for (int i = 0; i < type.getLength(); i++) {
					board[getX()][getY() + i] = type.getLength();
				}
			else if (dir == Direction.WEST)
				for (int i = 0; i < type.getLength(); i++) {
					board[getX() - i][getY()] = type.getLength();
				}
			else if (dir == Direction.EAST)
				for (int i = 0; i < type.getLength(); i++) {
					board[getX() + i][getY()] = type.getLength();
				}

		}

		return true;
	}


String toStringWithShips() {

		String fieldString = "";
		for (int n = 0; n < width; n++) {
			for (int m = 0; m < height; m++) {
				if (board[n][m] != WATER) {
					fieldString += board[n][m];

				} else {
					fieldString += ".";
				}
			}

			fieldString += "\n";
		}

		return fieldString;
	}
}



public enum ShipType {
    /**
     * The Minesweeper ship-type
     */
    MINESWEEPER {
        @Override
        public int getLength() {
            return 1;
        }
    }, 
    
    /**
     * The Battlecruise ship-type
     */
    BATTLECRUISER {
        @Override
        public int getLength() {
            return 2;
        }
    }, 
    
    /**
     * The Dreadnought ship-type
     */
    DREADNOUGHT {
        @Override
        public int getLength() {
            return 3;
        }
    }, 
    
    /**
     * The Flattop ship-type
     */
    FLATTOP {
        @Override
        public int getLength() {
            return 4;
        }
    };
    
    /**
     * Returns the ship-length of each ship-type
     * @return the length of the ship
     */
    public abstract int getLength();   
}




public enum Direction {
        /**
         * The North Direction (where y decreases)
         */
        NORTH, 
        
        /**
         * The East Direction (where x increases)
         */
        EAST, 
        
        /**
         * The South Direction (where y increases)
         */
        SOUTH, 
        
        /**
         * The West Direction (where x decreases)
         */
        WEST
    }



I want to place some ships randomly but my code tries to place them all in the upper left coordinate and after placing the first one, it cannot place the others because the place is no longer empty. Also it cannot place the ships in directions NORTH and WEST. When I try to place them in these directions I get this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

public class Test {

    static int width = 10;
    static int height = 10;
   
    static int x = (int)( Math.random() * 10);
    static int y = (int)(Math.random() * 10);
    

    public static void main(String[] args){
        
        Sea s = new Sea(width , height);
        
        s.addShip(ShipType.DREADNOUGHT, Direction.EAST, x, y);
        s.addShip(ShipType.FLATTOP, Direction.WEST, x, y);
        s.addShip(ShipType.BATTLECRUISER, Direction.SOUTH, x, y);
        s.addShip(ShipType.MINESWEEPER, Direction.NORTH, x, y);
        
   System.out.println(s.toStringWithShips());
        
       
    }
}





The output should look like this when I place some ships:
...1......
.22.....1.
..........
..333....3
.........3
.........3
4444......
..........
..1...2...
......2...



How can I fix these these problems?
I really appreciate all your help. :smile2:/>/>

Is This A Good Question/Topic? 0
  • +

Replies To: Why do I get these errors? Battleship-Java

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4318
  • View blog
  • Posts: 12,100
  • Joined: 18-April 07

Re: Why do I get these errors? Battleship-Java

Posted 06 June 2014 - 11:26 AM

Let's look at this bit of code to start...

    static int x = (int)( Math.random() * 10);
    static int y = (int)(Math.random() * 10);
    

    public static void main(String[] args){
        
        Sea s = new Sea(width , height);
        
        s.addShip(ShipType.DREADNOUGHT, Direction.EAST, x, y);
        s.addShip(ShipType.FLATTOP, Direction.WEST, x, y);
        s.addShip(ShipType.BATTLECRUISER, Direction.SOUTH, x, y);
        s.addShip(ShipType.MINESWEEPER, Direction.NORTH, x, y);
        
   System.out.println(s.toStringWithShips());
        
       
    }



In the code above we start with x and y being set to some random number. You use this value to place each ship. But I ask you, where does X and Y actually change here? Hold that thought for a moment while we take a look at "Sea" and addShip.

When we create a Sea we pass it the width and height. But nothing to do with X or Y, so these values are left out. You then go to add a ship based on these values of X and Y. These values need to change when adding a ship. You are not using the ones passed to addShip because you are using getX and getY which uses the ones in Sea.

Now going back to the first part, you should have a random value generated, passed to addShip, it uses those values (not the ones in Sea) to place the ship. Then you regenerate new X and Y in main() and place your next ship. If it fails, you don't place the ship, you detect the error back in main, regenerate new X and Y and try placing the ship again. When a ship is successfully placed, you could have a list within Sea to keep track of position of all ships from that point forward. But for placing, you need to change your X and Y before each ship is added.

:)

This post has been edited by Martyr2: 06 June 2014 - 11:31 AM

Was This Post Helpful? 1
  • +
  • -

#3 java101*  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-June 14

Re: Why do I get these errors? Battleship-Java

Posted 06 June 2014 - 12:48 PM

Thanks a lot!That was great help! I could finally solve the problem. :smile2:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1