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:

// 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);

//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

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.

04-24-2011, 11:17 PM

ra4king

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.

04-24-2011, 11:19 PM

lolerskates2695

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.

04-25-2011, 01:05 AM

ra4king

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.