Results 1 to 8 of 8
  1. #1
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default Battleship Game - Pieces lay on top of eachother.

    Hey guys, I have a project to make a game of battleship. Everything works except that about every 3/5 times you play the game, it places a ship on top of another. I'll give you my code. I have in comments where I think the problem is and why. Any ideas? Thanks.
    MainPanel.java:
    Java Code:
    /**
     *MainPanel.java
     *@Author
     *
     */
    
     import java.awt.*;  // Color, Dimension, etc.
     import java.awt.event.*;  // ActionListener, ActionEvent, etc.
     import javax.swing.*;  // JPanel, JButton, JOptionPane, etc.
    
    
     public class MainPanel extends JPanel
     {
     	// Instance variables: GUI components and others
     	private final int ROWS = 10;
     	private final int COLS = 10;
     	
     	//Variable for the board of play.
     	private int[][] board;
     	
     	//Counter for how many moves have been made.
     	private int MOVES = 0;
    
     	//Values for gridButtons when clicked or unclicked
     	public static final int EMPTY = 100;
     	public static final int HIT = 10;
     	public static final int MISS = 20;
     	
     	//Variable of the number of ships
    	private static final int NUM_SHIPS = 5;
    
    	//private JPanel gridPanel;
    	private ImageIcon waterIcon;
    
    	//Ship variable for the ship class in Ship.java
    	private Ship ship[];
    
    	//Variable for various components on the board
    	private JLabel titleLabel;
    	private JPanel titlePanel, buttonPanel, gridPanel;
    	private JButton playButton, resetButton, quitButton;
    	private JButton[][] gridButton;
    
    	//Variables for the listeners
    	private ButtonListener buttonListener = new ButtonListener();
    	private GridListener gridListener = new GridListener();
    
    
     	// Constructor: sets up the GUI
     	public MainPanel()
     	{
     		//Set up each piece of the GUI interface
     		Font labelFont = new Font("Serif", Font.BOLD, 25);
     		titleLabel = new JLabel("Let's Play Battleship!");
     		titleLabel.setFont(labelFont);
     		
     		titlePanel = new JPanel();
     		titlePanel.add(titleLabel);
    
     		//Edit the buttons of the interface
     		buttonPanel = new JPanel();
    		playButton = new JButton("Play");
    		playButton.addActionListener(buttonListener);
    
    		resetButton = new JButton("Reset");
    		resetButton.setEnabled(false);
    		resetButton.addActionListener(buttonListener);
    
    		quitButton = new JButton("Quit");
    		quitButton.addActionListener(buttonListener);
    
    		//add the buttons to the interface
    		buttonPanel.add(playButton);
    		buttonPanel.add(resetButton);
    		buttonPanel.add(quitButton);
    
     		// Background image
     		waterIcon = new ImageIcon("water.gif");
    
     		// Create space for the gridButton array
     		gridButton = new JButton[ROWS][COLS];
    
    		// Create gridPanel
    		gridPanel = new JPanel();
    
     		// Set gridPanel to have a GridLayout
     		gridPanel.setLayout(new GridLayout(ROWS,COLS));
    
     		// Create and add gridButtons to gridPanel
     		for (int r = 0; r < gridButton.length; r++)
     		{
     			for (int c = 0; c < gridButton[r].length; c++)
     			{
     				gridButton[r][c] = new JButton();
     				gridButton[r][c].setIcon(waterIcon);
     				gridButton[r][c].setEnabled(false);
     				gridButton[r][c].addActionListener(gridListener);
     				gridPanel.add(gridButton[r][c]);
     			}//end for cols
     		}//end for row
    
     		// MainPanel: setLayout
     		this.setLayout(new BorderLayout());
     		this.add(titlePanel, "North");
     		this.add(gridPanel, "Center");
     		this.add(buttonPanel, "South");
     		this.setPreferredSize(new Dimension(650, 650));
     	}//end public MainPanel
    
     	//Initialize the variables of each space on the board.
     	public void initializeBoard()
     	{
     		// Create space for board: 2D (ROWSxCOLS) integer array
     		board = new int[ROWS][COLS];
    
     		//Initialize board array to hold EMPTY values
     		for(int r = 0; r < board.length; r++)
            {
                for(int c = 0; c < board.length; c++)
                {
                    board[r][c] = EMPTY;
                }//end for columns
            }//end for rows
     	}//end public void initializeBoard
    
     	//Initialize the ships
     	public void initializeShips()
     	{
     		ship = new Ship[5];
            for(int type = 0; type < ship.length; type++)
            {
                ship[type] = new Ship(type);
                ship[type].setType(type);
            }//end for
     	}//end initializeShips
    
     	// Listener for button pressing events
     	private class ButtonListener implements ActionListener
     	{
     		public void actionPerformed(ActionEvent evt)
     		{
     			if(evt.getSource() == playButton)
     			{
     				handlePlayButton();
     			}//end if
     			if(evt.getSource() == resetButton)
     			{
     				handleResetButton();
     			}//end if
     			if(evt.getSource() == quitButton)
     			{
     				System.exit(0);
     			}//end if
     		}//end public void actionPerformed
     	}//end private class buttonListener
    
     	//Listener for grid pressing events
     	private class GridListener implements ActionListener
     	{
     		public void actionPerformed(ActionEvent evt)
     		{
     			for (int r = 0; r < gridButton.length; r++)
     				for(int c = 0; c < gridButton.length; c++)
     				{
     					if (evt.getSource() != gridButton[r][c])
     					{
     						continue;
     					}//end if
     					handleGridButton(r,c);
     					return;
     				}//end for
     			}//end public void actionPerformed
     	}//end private class GridListner
    
     	//When the play button is pressed, initialize the board, ships, and change the titleLabel.
     	public void handlePlayButton()
     	{
     		initializeBoard();
     		initializeShips();
     		titleLabel.setText("Ships Placed. Make your move.");
     		shipPlace();
     		enableGrid(true);
     		playButton.setEnabled(false);
     		resetButton.setEnabled(true);
     		MOVES = 0;
     	}//end public void handlePlayButton
     	
     	//When the reset button is pressed, empty all of the ship variables as well as make all values on the board null.
     	public void handleResetButton()
     	{
     		Ship[] sNum = ship;
     		for(int r = 0; r < gridButton.length; r++)
     		{
     			for(int c = 0; c < gridButton.length; c++)
     			{
     				gridButton[r][c].setIcon(waterIcon);
     				gridButton[r][c].setBackground(null);
     				gridButton[r][c].setText(null);
     				gridButton[r][c].setEnabled(false);
     			}//end for cols
     		}//end for rows
     		for(int i = 0; i < NUM_SHIPS; i++)
     		{
     	 		sNum[i] = null;
     	 		sNum[i] = null;
     	 		sNum[i] = null;
     	 		sNum[i] = null;
     		}//end for
    
     		enableGrid(false);
     		playButton.setEnabled(true);
     	}//end handleResetButton
     	
     	//Method to enable every space on the grid.
     	public void enableGrid(boolean enable)
     	{
     		for (int r = 0; r < gridButton.length; r++)
     		{
     			for(int c = 0; c < gridButton.length; c++)
     			{
     				gridButton[r][c].setEnabled(enable);
     			}//end for cols
     		}//end for rows
     	}//end enableGrid
     	
     	//Initialize the ship placing by finding random rows, columns, and directions to place the ship.
     	public void shipPlace()
     	{
     		int randCol;
     		int randRow;
     		int direct;
     		for(int ships = 0; ships < NUM_SHIPS; ships++)
     		{
     			do
     			{
     				randCol = (int)(Math.random() * 10);
     				randRow = (int)(Math.random() * 10);
     				direct = (int)(Math.random() * 4);
     			}while(!validSpaces(ship[ships], randCol, randRow, direct));
     		}//end for
     	}//end findPath
     	
     	//Decide if the length of the ship will fit into the length of the row/column is has been placed.
     	public boolean validSpaces(Ship ship, int column, int row, int direction)
     	{
     		//int startDirection = direction;
            //int direct = startDirection;
            int shipLength = ship.getLength();
            int minR, maxR, minC, maxC;
            do
            {
                minR = maxR = row;
                minC = maxC = column;
                switch(direction)
                {
                case 0:
                    minR = (row - shipLength) + 1;
                    break;
                case 1:
                    maxR = (row + shipLength) - 1;
                    break;
                case 2:
                    minC = (column - shipLength) + 1;
                    break;
                case 3:
                    maxC = (column + shipLength) - 1;
                    break;
                }//end switch direction
                direction = (direction + 1) % 4;
            } while(!validSpots(ship, minR, minC, maxR, maxC));
            placeShip(ship, minR, minC, maxR, maxC);
    
            return validSpots(ship, minR, minC, maxR, maxC);
        }
    
     	//If the length is valid, now test if there are already ships placed in the spots given
     	//THIS IS WHERE THE PROBLEM IS....I THINK IT ALWAYS RETURNS TRUE BECAUSE IT DOESN'T GET PAST THE FIRST IF STATEMENT
     	public boolean validSpots(Ship sNum, int startR, int startC, int endR, int endC)
        {
        	boolean valid = false;
            if(startR >= 0 && endR < 10 && startC >= 0 && endC < 10)
            {
                for(int r = startR; r <= endR; r++)
                {
                    for(int c = startC; c <= endC; c++)
                    {
                        if(board[r][c] != EMPTY || board[r][c] == 5|| board[r][c] == 0 || board[r][c] == 2 || board[r][c] == 1 || board[r][c] == 3 || board[r][c] == 4)
                        {
                            valid = false;
                        }//end if
                    }//end for columns
                }//end for rows
                valid = true;
            }//end if
            else
            {
                valid = false;
            }//end else
            return valid;
        }//end public boolean validSpots
    
        public void placeShip(Ship sNum, int startR, int startC, int endR, int endC)
        {
            for(int r = startR; r <= endR; r++)
            {
                for(int c = startC; c <= endC; c++)
                {
                    board[r][c] = sNum.getType();
                }//end for columns
            }//end for rows
        	sNum.setStartRow(startR);
            sNum.setEndRow(endR);
            sNum.setStartCol(startC);
            sNum.setEndCol(endC);
        }//end placeShip
    
     	// Button Listener handler methods
     	public void handleGridButton(int r, int c)
     	{
                if(board[r][c] == EMPTY)
                {
                    //board[r][c] = 106;
                    gridButton[r][c].setBackground(Color.black);
                    board[r][c] = MISS;
                    MOVES++;
                }//end if
                
                //The following is empty because if they continue to click something that is already hit, nothing should happen.
                else if(board[r][c] == HIT)
                {
                }//end else if
                else if(board[r][c] == MISS)
                {
                }//end else if
                else
                {
                	int type = board[r][c];
                    Ship shipNum = ship[type];
                    board[r][c] = HIT;
                        gridButton[r][c].setBackground(Color.green);
                        shipNum.addHit();
                        MOVES++;
                        
                        //if the ship is sunk, display the description in the grid buttons
                        if(shipNum.getSunk())
                        {
                            String shipDescription = shipNum.getDescription();
                            for(int row = shipNum.getStartRow(); row <= shipNum.getEndRow(); row++)
                            {
                                for(int col = shipNum.getStartCol(); col <= shipNum.getEndCol(); col++)
                                {
                                    gridButton[row][col].setText(shipDescription);
                                }//end for cols
                            }//end for rows
                            
                            //if the ships are all sunk, the player has won. Tell them - also, display the amount of moves it took
                            if(allShipsSunk())
                            {
                                JOptionPane.showMessageDialog(null, "You won!");
                                setEnabled(false);
                                titleLabel.setText("You beat the game in " + MOVES + " moves. \n Press reset to play again.");
                            }//end if allShipsSunk
                        }//end if curShip.getSunk
                    }//end else
                }//end public void handleGridButton
    
     	//Method to decide if all of the ships are sunk.
        public boolean allShipsSunk()
        {
            Ship sNum[] = ship;
            int length = sNum.length;
            for(int i = 0; i < length; i++)
            {
                Ship s = sNum[i];
                if(!s.getSunk())
                {
                    return false;
                }//end if
            }//end for
            return true;
        }//end boolean allShips Sunk
     }//end public class mainpanel
    Ship.java:
    Java Code:
    public class Ship
    {
    	private static final String[ ] shipDescription = {"Aircraft Carrier", "Battleship", "Cruiser", "Submarine", "Destroyer"};
    	private static final int[] shipLength = {5, 4, 2, 3, 3};
    
    	private int type, length, hits, startRow, endRow, startCol, endCol;
    	private String description;
    	private boolean isSunk;
    	//private boolean isPlaced;
    
    
    	public Ship(int initType)
        {
            type = initType;
            description = shipDescription[type];
            length = shipLength[type];
            startRow = 0;
            startCol = 0;
            endCol = 0;
            endRow = 0;
            hits = 0;
            //isPlaced = false;
            isSunk = false;
        }//end public Ship
        public int getType()
        {
        	return type;
        }//end public int getType
    
        public int getHits()
        {
        	return hits;
        }//end public int getHits
    
        public int getStartRow()
        {
        	return startRow;
        }
    
        public int getEndRow()
        {
        	return endRow;
        }
    
        public int getStartCol()
        {
        	return startCol;
        }
    
        public int getEndCol()
        {
            return endCol;
        }
    
        public int getLength()
        {
        	return length;
        }//end public int getLength
    
        public boolean getSunk()
        {
        	return isSunk;
        }
    
        public String getDescription()
        {
            return description;
        }
    
        public void setType(int updateType)
        {
        	type = updateType;
        }
    
        public void setShipType(String updateShipType)
        {
        	description = updateShipType;
        }
    
        public void setLength(int updateLength)
    	{
    		length = updateLength;
    	}
    
        public void setStartRow(int updateRow)
        {
            startRow = updateRow;
        }
    
        public void setEndRow(int updateRow)
        {
            endRow = updateRow;
        }
    
        public void setStartCol(int updateCol)
        {
            startCol = updateCol;
        }
    
        public void setEndCol(int updateCol)
        {
            endCol = updateCol;
        }
    
    
        public void addHit()
        {
        	hits++;
        	if(hits == length)
        	{
        		isSunk = true;
        	}
        	else
        	{
        		isSunk = false;
        	}
        }
    
        public String toString()
        {
        	return description;
        }
    }//end public class Ship
    Battleship2.java:
    Java Code:
    //import java.awt.*;
    import javax.swing.*;
    
    public class Battleship2
    {
        public static void main(String args[])
        {
            JFrame frame = new JFrame("Let's Play Battleship!");
    
            frame.setDefaultCloseOperation(3);
    
            MainPanel mainPanel = new MainPanel();
    
            frame.getContentPane().add(mainPanel);
    
            frame.pack();
    
            frame.setVisible(true);
        }//end main
    }//end public class Battleship2

  2. #2
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    Not too sure of the odds of this happening, but pretty much the exact same issue with my battleship game is being discussed in this thread. Not sure if this will be of any help at all to you:

    The last stumbling block to finishing a project: Checking if already used

  3. #3
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    eh..still doesn't work. Hoping someone can help us.

  4. #4
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    I would suggest looking into the placeShip method.

  5. #5
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by ra4king View Post
    I would suggest looking into the placeShip method.
    Are you saying that you know the problem is within the placeShip method, or are you giving me a place to start? I attempted changing things within the placeShip method but I haven't had any luck.

  6. #6
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    I'm just giving you a place to start because that looks like the most obvious place to start in. Try debugging it line by line.

    EDIT: Oh I didn't see the validSpots method. That looks more suspicious, especially the long if statement.

  7. #7
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Agreed. I've tried everything; including what you've suggested. I posted on here hoping someone would have a greater knowledge than I do and be able to give more in-depth assistance.

  8. #8
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    The problem here is that there is a ton of code, with little knowledge of what most variables mean. So I (and I'm sure others) can't help much unless you specifically explain those two methods. Help us understand so we can help you.

Similar Threads

  1. Battleship Game - really need help
    By thrashsynergy in forum Java Applets
    Replies: 5
    Last Post: 04-25-2011, 08:21 PM
  2. BattleShip game ship on top of ship
    By linux1man in forum New To Java
    Replies: 2
    Last Post: 06-03-2009, 01:42 PM
  3. Battleship game
    By kathyla18 in forum New To Java
    Replies: 2
    Last Post: 02-26-2009, 10:42 PM
  4. Java Battleship Game Help PLEASE
    By mars_red in forum New To Java
    Replies: 0
    Last Post: 02-12-2008, 02:09 AM
  5. Java BattleShip game help
    By mars_red in forum Advanced Java
    Replies: 0
    Last Post: 02-12-2008, 01:58 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •