Facebook
From Gentle Bongo, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 201
  1. import java.util.Random;
  2.  
  3. import javax.swing.JFrame;
  4. import javax.swing.JButton;
  5. import javax.swing.JPanel;
  6. import javax.swing.JLabel;
  7.  
  8. import java.awt.Dimension;
  9. import java.awt.FlowLayout;
  10. import java.awt.Color;
  11.  
  12. import java.awt.event.ActionListener;
  13. import java.awt.event.ActionEvent;
  14.  
  15. /**
  16.  * Simulates solitaire play of the game Battleship.  Try to locate all parts of all 5 enemy ships.
  17.  * Extends the JFrame class.
  18.  *
  19.  * @author  Spencer DeBuf
  20.  * @version 1.0
  21.  */
  22.  
  23. public class BattleshipFrame extends JFrame
  24. {    
  25.     /** SquarePanel array representing the playing grid of 8 rows by 8 columns*/
  26.     SquarePanel panel[][] = new SquarePanel[8][8];
  27.    
  28.     /** Jbutton array representing the 64 possible guesses*/
  29.     JButton button[][] = new JButton[8][8];
  30.    
  31.     /** InfoPanel to display gameplay information*/
  32.     InfoPanel info;
  33.    
  34.     /** JFrame containing a question dialog displayed at the end of a game*/
  35.     JFrame playAgain;
  36.    
  37.     /** Color representing the default color of each JButton*/
  38.     Color defaultColor;
  39.    
  40.     /** Integer representing the number of guesses made*/
  41.     int guesses = 0;
  42.    
  43.     /** Static Integer representing the length of the ship, used in the placement of the ships*/
  44.     static int length;    
  45.    
  46.     /** Array of Integers used for storing the locations of the ships*/
  47.     static int board[][] = new int[8][8];
  48.    
  49.     /**
  50.      * Clears the play area for a new game.
  51.      */
  52.    
  53.     public void eraseBoard()
  54.     {
  55.         guesses = 0;
  56.         for (int x1 = 0; x1 < 8; x1++)
  57.         {
  58.             for (int y1 = 0; y1 < 8; y1++)
  59.             {
  60.                 board[x1][y1] = 0;  //erases the placement of the ships
  61.                 button[x1][y1].setBackground(defaultColor);//sets the buttons to their default color
  62.             }            
  63.         }
  64.        
  65.         info.guesses.setText("Guesses: " + guesses);//displays the number of guesses
  66.     }
  67.    
  68.     /**
  69.      * Displays a new JFrame asking the user if they wish to play another game.
  70.      */
  71.    
  72.     public void checkForPlayAgain()
  73.     {
  74.         playAgain = new JFrame();
  75.         playAgain.setLayout(new FlowLayout());
  76.         playAgain.setVisible(true);
  77.         JButton yes = new JButton("Yes");
  78.         JButton no = new JButton("No");
  79.         JLabel playAgainLabel = new JLabel("Would you like to play again?");
  80.         playAgain.add(playAgainLabel);
  81.         playAgain.add(yes);
  82.         playAgain.add(no);
  83.         no.addActionListener(new ExitGame());
  84.         yes.addActionListener(new PlayAgain());
  85.         playAgain.setTitle("Play Again?");
  86.         playAgain.setDefaultCloseOperation(EXIT_ON_CLOSE);        
  87.         playAgain.pack();      
  88.     }        
  89.    
  90.     /**
  91.      * Class Constructor.  Displays the playing field on the JFrame
  92.      */
  93.    
  94.     public BattleshipFrame()
  95.     {
  96.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  97.         setPreferredSize(new Dimension(425,545));
  98.         //setResizable(false);
  99.         setLayout(new FlowLayout(1,0,0));
  100.         setVisible(true);
  101.         setTitle("Battleship");
  102.         setResizable(false);
  103.        
  104.         //populates the board with panels with JButtons on them
  105.         for (int r = 0; r < 8; r++)
  106.         {
  107.             for (int c = 0; c < 8; c++)
  108.             {                
  109.                 panel[r][c] = new SquarePanel();
  110.                 button[r][c] = new JButton();
  111.                 panel[r][c].setLayout(new FlowLayout());
  112.                 button[r][c].setPreferredSize(new Dimension(48,48));
  113.                 button[r][c].addActionListener(new ButtonPressed(r,c));
  114.                 panel[r][c].add(button[r][c]);
  115.                 add(panel[r][c]);
  116.             }
  117.         }              
  118.        
  119.         defaultColor = button[1][1].getBackground();//set the default Color of the JButtons        
  120.         info = new InfoPanel();          
  121.         add(info);//adds the InfoPanel to the bottom of the JFrame        
  122.         pack();      
  123.     }
  124.    
  125.     /**
  126.      * Class to be called when the buttons are pressed.  Implements ActionListener Interface.
  127.      */
  128.    
  129.     public class ButtonPressed implements ActionListener
  130.     {  
  131.         int r;//integer to store the value of which row the button that was pressed is in
  132.         int c;//integer to store the value of which column the button that was presses is in
  133.        
  134.         /**
  135.          * Class Constructor.
  136.          *
  137.          * @param   row which row the button pressed resides in
  138.          * @param   column  which column the butotn pressed resides in
  139.          */
  140.        
  141.         public ButtonPressed(int row, int column)
  142.         {
  143.             r = row;
  144.             c = column;
  145.         }
  146.        
  147.         /**
  148.          * Checks if the guess was a hit or miss.  Displays the result on the JFrame.
  149.          *
  150.          * @param   evt the specific ActionEvent that was triggered
  151.          */
  152.        
  153.         public void actionPerformed(ActionEvent evt)
  154.         {
  155.             //if the guess was a miss            
  156.             if (board[r][c] == 0)
  157.             {
  158.                 button[r][c].setBackground(Color.black);
  159.                 board[r][c] = 0;
  160.             }
  161.            
  162.             //if the guess hit a minesweeper
  163.             if (board[r][c] == 2)
  164.             {
  165.                 button[r][c].setBackground(Color.green);
  166.                 board[r][c] = -1;
  167.             }
  168.            
  169.             //if the guess hit a frigate
  170.             if (board[r][c] == 3)
  171.             {
  172.                 button[r][c].setBackground(Color.blue);
  173.                 board[r][c] = -1;
  174.             }
  175.            
  176.             //if the guess hit a cruiser
  177.             if (board[r][c] == 4)
  178.             {
  179.                 button[r][c].setBackground(Color.red);
  180.                 board[r][c] = -1;
  181.             }
  182.            
  183.             //if the guess hit a battleship
  184.             if (board[r][c] == 5)
  185.             {
  186.                 button[r][c].setBackground(Color.yellow);
  187.                 board[r][c] = -1;
  188.             }
  189.            
  190.             guesses++;
  191.             info.guesses.setText("Guesses: " + guesses);    
  192.            
  193.             if (checkForGameOver())
  194.             {
  195.                 checkForPlayAgain();
  196.             }          
  197.         }          
  198.     }
  199.    
  200.     /**
  201.      * Exits the application.  Implements the ActionListener Interface
  202.      */
  203.    
  204.     public class ExitGame implements ActionListener
  205.     {
  206.        
  207.         /**
  208.          * Exits the application.
  209.          *
  210.          * @param   evt the specific ActionEvent that was triggered
  211.          */
  212.        
  213.         public void actionPerformed(ActionEvent evt)
  214.         {
  215.             System.exit(0);
  216.         }
  217.     }
  218.    
  219.     /**
  220.      * Calls the methods necessary for replaying the game.  Implements the ActionListener Interface.
  221.      */
  222.    
  223.     public class PlayAgain implements ActionListener
  224.     {
  225.        
  226.         /**
  227.          * Calls the methods necessary for replaying the game.
  228.          *
  229.          * @param   evt the specific ActionEvent that was triggered
  230.          */
  231.        
  232.         public void actionPerformed(ActionEvent evt)
  233.         {
  234.             eraseBoard();
  235.             for (int i = 2; i <= 5; i++)
  236.             {
  237.                 populateBoard(i);
  238.             }
  239.            
  240.             playAgain.setVisible(false);//hides the window asking the user to play again          
  241.         }
  242.     }
  243.    
  244.     /**
  245.      * Checks if all of the ships have been hit.
  246.      *
  247.      * @return  false if the game is not over, true if the game is over
  248.      */
  249.    
  250.     public boolean checkForGameOver()
  251.     {
  252.         for (int row = 0; row < 8; row++)
  253.         {
  254.             for (int col = 0; col < 8; col++)
  255.             {
  256.                 //if the board doesnt contain a ship or if it contains a ship but the position has already been located
  257.                 if (board[row][col] != 0 && board[row][col] != -1)
  258.                 {
  259.                     return false;
  260.                 }
  261.             }
  262.         }
  263.         return true;
  264.     }
  265.    
  266.     /**
  267.      * Fills the board randomly with the 4 ships.
  268.      *
  269.      * @param   lengthOfShip    the length of the specific ship currently being placed
  270.      */
  271.    
  272.     public static void populateBoard(int lengthOfShip)
  273.     {
  274.         /** instance used for randomly placing the ships*/
  275.         Random random = new Random();
  276.        
  277.         /** used to tell the loop whether to keep trying to place the ship or not*/
  278.         boolean cont = false;
  279.        
  280.         /** used to designate whether the ship should go backwards or forwards*/
  281.         boolean orientation = false;
  282.        
  283.         /** used to designate whether the ship should be placed horizontally or vertically*/
  284.         boolean direction;
  285.        
  286.         /**integer representing the potential x value of the ship position*/
  287.         int x;
  288.        
  289.         /**integer representing the potential y value of the ship position*/
  290.         int y;
  291.        
  292.         /** integer representing whethere a specific square is empty or not*/
  293.         boolean emptySquare = true;
  294.        
  295.         length = lengthOfShip;
  296.        
  297.         while (!cont)
  298.         {    
  299.             emptySquare = true;        
  300.        
  301.             orientation = random.nextBoolean();
  302.             direction = random.nextBoolean();
  303.        
  304.             x = random.nextInt(8);
  305.             y = random.nextInt(8);            
  306.        
  307.             //vertical
  308.             if (orientation)
  309.             {            
  310.                 //placed to the right
  311.                 if (direction)
  312.                 {
  313.                
  314.                     //both points are one the board
  315.                     if (y + length <= 7)
  316.                     {                  
  317.                         for (int i = y; i < y + length; i++)
  318.                         {
  319.                             //square is already occupied
  320.                             if (board[x][i] != 0)
  321.                             {
  322.                                 emptySquare = false;
  323.                             }
  324.                         }  
  325.                    
  326.                         //ship can be placed here
  327.                         if (emptySquare)
  328.                         {
  329.                             for (int i = y; i < y + length; i++)
  330.                             {
  331.                                 board[x][i] = length;
  332.                             }                          
  333.                             return;
  334.                         }
  335.                     }
  336.                 }
  337.                
  338.                 //placed to the left
  339.                 else
  340.                 {
  341.                     if (y - length >= 0)
  342.                     {
  343.                         for (int i = y; i > y - length; i--)
  344.                         {
  345.                             //square is already occupied
  346.                             if (board[x][i] != 0)
  347.                             {
  348.                                 emptySquare = false;
  349.                             }
  350.                         }
  351.                    
  352.                         //ship can be placed here
  353.                         if (emptySquare)
  354.                         {
  355.                             for (int i = y; i > y - length; i--)
  356.                             {
  357.                            
  358.                                 board[x][i] = length;                                          
  359.                                                              
  360.                             }
  361.                             return;
  362.                         }
  363.                     }
  364.                 }
  365.                    
  366.             }            
  367.        
  368.             //horizontal
  369.             if (!orientation)
  370.             {
  371.                 //placed upward
  372.                 if (!direction)
  373.                 {          
  374.                     //both points are one the board
  375.                     if (x - length >= 0)
  376.                     {                                                    
  377.                         for (int i = x; i > x - length; i--)
  378.                         {
  379.                             //square is already occupied
  380.                             if (board[i][y] != 0)
  381.                             {
  382.                                 emptySquare = false;
  383.                             }
  384.                            
  385.                         }
  386.                        
  387.                         //ship can be placed here
  388.                         if (emptySquare)
  389.                         {
  390.                             for (int i = x; i > x - length; i--)
  391.                             {
  392.                                 board[i][y] = length;                              
  393.                            
  394.                             }
  395.                             return;
  396.                         }
  397.                     }
  398.                 }
  399.                
  400.                 //placed downward
  401.                 else
  402.                 {
  403.                     if (x + length <= 7)
  404.                     {
  405.                         for (int i = x; i < x + length; i++)
  406.                         {  
  407.                             //square is already occupied
  408.                             if (board[i][y] != 0)
  409.                             {
  410.                                 emptySquare = false;
  411.                             }
  412.                            
  413.                         }
  414.                        
  415.                         //ship can be placed here
  416.                         if (emptySquare)
  417.                         {
  418.                             for (int i = x; i < x + length; i++)
  419.                             {
  420.                            
  421.                                 board[i][y] = length;                        
  422.                             }
  423.                             return;
  424.                         }
  425.                     }
  426.                 }
  427.             }
  428.         }          
  429.     }    
  430. }
  431.