Results 1 to 6 of 6
  1. #1
    thrashsynergy is offline Member
    Join Date
    Apr 2011
    Posts
    1
    Rep Power
    0

    Default Battleship Game - really need help

    First time poster, but this program is killing me and I really need a little help in one section in particular. I am supposed to make a program that lets the computer randomly place the different battleships, and then allow the user to try and find them. I am about 99% sure the issue is occurring somewhere in the placeShips(), validPath() and setShips() methods. I am going to go ahead and post all of my 3 classes so that you can compile and run it on your own systems. If anyone thinks they have figured it out, please let me know!

    BATTLESHIP CLASS
    import java.awt.*;
    import javax.swing.*;


    public class Battleship {

    public static void main (String[] args)
    {
    JFrame frame = new JFrame("Battleship");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);

    MainPanel mainPanel = new MainPanel();
    frame.getContentPane().add(mainPanel);

    frame.pack()

    frame.setVisible(true);
    }
    }


    MainPanel Class - WHERE ALL THE PROBLEMS ARE
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.Random;


    public class MainPanel extends JPanel{
    //Enumerated values for placement directions
    private static final int UP = 0;
    private static final int DOWN = 1;
    private static final int LEFT = 2;
    private static final int RIGHT = 3;
    private static final int NUM_DIRECTIONS = 4;

    //enumerated values for different ships
    private static final int BSHIP = 0;
    private static final int AIRCARRIER = 1;
    private static final int CRUISER = 2;
    private static final int SUBMARINE = 3;
    private static final int DESTROYER = 4;
    private static final int NUM_SHIPS = 5;

    //enumerated values for hits, misses and unplayed tiles
    private static final int UNCLICKED = 6;
    private static final int EMPTY = 7;
    private static final int HIT = 8;
    private static final int MISS = 9;

    //enumerated values for board colors
    private static final Color COLOR_UNCLICKED = Color.blue;
    private static final Color COLOR_MISS = Color.white;
    private static final Color COLOR_HIT = Color.red;

    //final board set up
    private final int ROWS = 8;
    private final int COLS = 8;
    private int[][] board;

    //create ship array for initializing ships
    private Ships[] ship;

    //create panels, buttons and labels
    private JLabel title;
    private JPanel titlePanel;
    private JPanel buttonPanel;
    private JButton playButton;
    private JButton resetButton;
    private JButton quitButton;
    private JButton[][] gridButton;
    private JPanel gridPanel;

    //create grid listener and button listener
    private ButtonListener theListener = new ButtonListener();
    private GridListener gridListener = new GridListener();

    //create random number generator
    private Random generator = new Random();


    //constructor
    public MainPanel()
    {
    //initialize board and ships
    initializeBoard();
    initializeShips();

    //create title label and panel
    title = new JLabel("BATTLESHIP!");
    titlePanel = new JPanel();
    titlePanel.add(title);

    //create button panel and buttons
    buttonPanel = new JPanel();
    playButton = new JButton("Play!");
    playButton.addActionListener(theListener);
    resetButton = new JButton("Reset!");
    resetButton.setEnabled(false);
    resetButton.addActionListener(theListener);
    quitButton = new JButton("Quit");
    quitButton.addActionListener(theListener);
    buttonPanel.add(playButton);
    buttonPanel.add(resetButton);
    buttonPanel.add(quitButton);

    //create grid buttons and grid
    gridButton = new JButton[8][8];
    gridPanel = new JPanel();
    gridPanel.setLayout(new GridLayout(8, 8));

    //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].setBackground(COLOR_UNCLICKED);
    gridButton[r][c].setEnabled(false);
    gridButton[r][c].addActionListener(gridListener);
    gridPanel.add(gridButton[r][c]);
    }

    //add layout and panels
    this.setLayout(new BorderLayout());
    this.add(titlePanel, "North");
    this.add(gridPanel, "Center");
    this.add(buttonPanel, "South");
    this.setPreferredSize(new Dimension(650, 600));

    }

    //initialize board
    public void initializeBoard()
    {
    board = new int[8][8];
    for (int r = 0; r < board.length; r++)
    for (int c = 0; c < board.length; c++)
    {
    board[r][c] = UNCLICKED;
    }
    }

    //initialize ships
    public void initializeShips()
    {
    ship = new Ships[5];
    for(int shipType = 0; shipType < ship.length; shipType++)
    {
    ship[shipType] = new Ships(shipType);
    }
    }

    //gridlistener and buttonlistener
    private class ButtonListener implements ActionListener
    {
    public void actionPerformed(ActionEvent evt)
    {
    if (evt.getSource() == playButton)
    handlePlayButton();
    if (evt.getSource() == resetButton)
    handleResetButton();
    if (evt.getSource() == quitButton)
    System.exit(0);
    }
    }

    private class GridListener implements ActionListener
    {
    public void actionPerformed(ActionEvent evt)
    {
    for (int r = 0; r < gridButton.length; r++)
    for(int c = 0; c < gridButton[r].length; c++)
    {
    if (evt.getSource() != gridButton[r][c])
    continue;
    handleGridButton(r,c);
    return;
    }
    }
    }

    //play button = places ships, enables grid and disables play button
    public void handlePlayButton()
    {
    placeShips();
    gridEnable(true);
    playButton.setEnabled(false);
    }

    //randomly places ships
    public void placeShips()
    {
    int randomRow;
    int randomCol;
    int direction;
    for(int ships = 0; ships < NUM_SHIPS; ships++)
    {
    do
    {
    randomRow = generator.nextInt(8);
    randomCol = generator.nextInt(8);
    direction = generator.nextInt(4);
    }
    while(board[randomRow][randomCol] != 6 || validPath(ship[ships], randomRow, randomCol, direction) == false);
    }
    }

    //determines if random ship placement is valid
    public boolean validPath(Ships s, int r, int c, int d)
    {
    int length = s.getLength();
    boolean valid = false;
    int direction = d;
    int row = 0, col = 0;
    int maxR = 0, minR = 0, maxC = 0, minC = 0;

    switch (direction)
    {
    case 0: row = r - length + 1;
    minR = row;
    maxR = row + length - 1;
    break;
    case 1: row = r + length - 1;
    maxR = row;
    minR = row - length + 1;
    break;
    case 2: col = c - length + 1;
    minC = col;
    maxC = col + length - 1;
    break;
    case 3: col = c + length - 1;
    maxC = col;
    minC = col - length + 1;
    break;
    }

    for(int rows = minR; rows <= maxR; rows++)
    for(int cols = minC; cols <= maxC; cols++)
    {
    if(row < 0 || col < 0 || row > 8 || col > 8 || board[rows][cols] != 6)
    {
    valid = false;
    }
    else
    {
    setsShips(s, minR, minC, maxR, maxC);
    valid = true;
    }
    }
    return valid;
    }

    //sets ships on board
    public void setsShips(Ships shipnum, int startRow, int startColumn, int endRow, int endColumn)
    {
    for(int r = startRow; r <= endRow; r++)
    for(int c = startColumn; c <= endColumn; c++)
    {
    board[r][c] = shipnum.getType();
    }
    shipnum.setStartRow(startRow);
    shipnum.setEndRow(endRow);
    shipnum.setStartCol(startColumn);
    shipnum.setEndCol(endColumn);
    }

    //reset button = resets grid, disables grid, enables play button
    public void handleResetButton()
    {
    for (int r = 0; r < gridButton.length; r++)
    for (int c = 0; c < gridButton[r].length; c++)
    {
    gridButton[r][c].setBackground(COLOR_UNCLICKED);
    gridButton[r][c].setEnabled(false);
    }
    gridEnable(false);
    playButton.setEnabled(true);
    }

    //enable or disable grid
    public void gridEnable(boolean enable)
    {
    for (int r = 0; r < gridButton.length; r++)
    {
    for(int c = 0; c < gridButton[r].length; c++)
    gridButton[r][c].setEnabled(enable);
    }
    }

    //handle grid button
    public void handleGridButton(int r, int c)
    {
    if (board[r][c] == UNCLICKED)
    {
    if (board[r][c] == EMPTY)
    {
    board[r][c] = MISS;
    gridButton[r][c].setBackground(COLOR_MISS);
    }

    else
    {
    int shipType = board[r][c];
    Ships activeShip = ship[shipType];
    gridButton[r][c].setBackground(COLOR_HIT);
    activeShip.shipHit();
    if (activeShip.getSunk() == false)
    {
    String description = activeShip.getShipType();
    for (int row = activeShip.getStartRow(); row<= activeShip.getEndRow(); row++)
    for (int column = activeShip.getStartCol(); column<= activeShip.getEndCol(); column++)
    {
    gridButton[row][column].setText(description);
    }
    if (allSunk() == true)
    {
    JOptionPane.showMessageDialog(null, "You Win!");
    resetButton.setEnabled(true);
    }
    }
    }
    }
    }

    //check if all ships are sunk
    public boolean allSunk()
    {
    boolean allSunk = false;
    for(int ships = 0; ships < NUM_SHIPS; ships++)
    {if (ship[ships].getSunk() == false)
    {allSunk = false;}
    else
    {allSunk = true;}
    }
    return allSunk;
    }

    }

    Ship constructor
    public class Ships {
    //variables for ship construction
    private int type;
    private int hits;
    private int length;
    private int startRow;
    private int endRow;
    private int startCol;
    private int endCol;
    private boolean sunk;
    private String shipType;

    //constructor
    public Ships(int shipNum)
    {
    type = shipNum;
    switch (type)
    {
    case 0: length = 4;
    shipType = "Battleship";
    break;
    case 1: length = 5;
    shipType = "Aircraft Carrier";
    break;
    case 2: length = 3;
    shipType = "Cruiser";
    break;
    case 3: length = 3;
    shipType = "Submarine";
    break;
    case 4: length = 2;
    shipType = "Destroyer";
    break;
    }
    startRow = 0;
    endRow = 0;
    startCol = 0;
    endCol = 0;
    hits = 0;
    sunk = false;
    }

    //accessors
    public int getType()
    {
    return type;
    }

    public String getShipType()
    {
    return shipType;
    }

    public int getLength()
    {
    return length;
    }

    public int getHits()
    {
    return hits;
    }

    public boolean getSunk()
    {
    return sunk;
    }

    public int getStartRow()
    {
    return startRow;
    }

    public int getEndRow()
    {
    return endRow;
    }

    public int getStartCol()
    {
    return startCol;
    }

    public int getEndCol()
    {
    return endCol;
    }

    //mutators
    public void setType(int updateType)
    {
    type = updateType;
    }

    public void setShipType(String updateShipType)
    {
    shipType = updateShipType;
    }

    public void setLength(int updateLength)
    {
    length = updateLength;
    }

    public void setStartRow(int updateStartRow)
    {
    startRow = updateStartRow;
    }

    public void setEndRow(int updateEndRow)
    {
    endRow = updateEndRow;
    }

    public void setStartCol(int updateStartCol)
    {
    startCol = updateStartCol;
    }

    public void setEndCol(int updateEndCol)
    {
    endCol = updateEndCol;
    }

    //ShipHit = hits and sunk mutator
    public void shipHit()
    {
    hits += 1;
    if (hits == length)
    {
    sunk = true;
    }
    else
    {
    sunk = false;
    }
    }

    public String toString()
    {
    return shipType;
    }

    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default

    First, use code tags.
    Second, never rely on people running your code. Narrow your code down to a problem area.
    Third, you've not actually told us the problem.

  3. #3
    to_devendra is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    for(int r = startRow; r <= endRow; r++)
    for(int c = startColumn; c <= endColumn; c++)
    Should be
    for(int r = startRow; r < endRow; r++)
    for(int c = startColumn; c < endColumn; c++)


    Array ship has length of 5 and you are trying to access 6. For the time being I made it as
    Ships activeShip = ship[shipType-2];
    rather than
    Ships activeShip = ship[shipType];

    By making those changes ..your program is working.rest , you can see..if you have any concern than let me know.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default

    Oh look...a spoonfeed.

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

    Default

    Well, to defend to_devendra, he did explain the reason of the change, instead of just giving him the code. But still, we need to teach these newbies how to debug for themselves.

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

    Default

    Did you ever figure this out? If so, what was the problem?

Similar Threads

  1. BattleShip game ship on top of ship
    By linux1man in forum New To Java
    Replies: 2
    Last Post: 06-03-2009, 12:42 PM
  2. Battleship game
    By kathyla18 in forum New To Java
    Replies: 2
    Last Post: 02-26-2009, 09:42 PM
  3. Battleship help..im confused
    By stepjerd1 in forum Java 2D
    Replies: 4
    Last Post: 01-23-2009, 01:35 AM
  4. Java Battleship Game Help PLEASE
    By mars_red in forum New To Java
    Replies: 0
    Last Post: 02-12-2008, 01:09 AM
  5. Java BattleShip game help
    By mars_red in forum Advanced Java
    Replies: 0
    Last Post: 02-12-2008, 12: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
  •