Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

need help with this java program. the determination of ships in a grid is the ha

ID: 3676465 • Letter: N

Question

need help with this java program. the determination of ships in a grid is the hardest part.

2. Battleship is a guessing game between the user and the computer where each player tries to sink all of their opponent's ships. The user and computer each get a 10 by 10 grid with each individual square identified by a letter (A-3) and a number (1-10, or 0-9). At the beginning of the game, each player needs to arrange five different battle ships in consecutive squares (number determined by type of ship) either horizontally or vertically with no overlaps, i.e. only one ship can occupy any given square in a grid The table lists the number, type, and size of each ship that each player will arrange in their grid Number | Type of Ship | Size (# of squares Aircraft Carrier Battleship Cruiser Submarine Patrol Boat 4 After the ships have been placed, the game proceeds in rounds with each player taking turns picking squares in their opponent's grid. If a chose square is empty, control passes to the opponent; if a hit is scored, the player goes again. Once all the squares in a particular ship have been hit, that particular ship is sunk. The object of the game is to be the first to sink all your opponent's ships. Write a non-GUI Java application program that plays a game similar to Battleship. You will play against the computer. Follow the implementation notes below Implementation Notes . You must represent your boards using two-dimensional arrays or an ArrayList At the beginning, allow the user to exit or proceed at this point. Next (if they proceed), ask the user if they want to restart a previously saved game or start a nevw game. In the first case, load the saved grids for the user and the computer. In the second case, create new blank grids for the user and the computer If this is a new game, then the user and the computer need to populate their respective grids The user should be prompted for a starting square (column, row) and orientation for each ship. The computer should place its ships randomly Remember to check for grid boundaries and ensure that none of the ships overlap! o o o There should be two modes to your game o Normal mode o Demo mode In Normal mode: Your program should display the user and computer grids side by side with the user grid displaying the location of each ship and the computer grid initially blank. The user will go first and choose a square. The computer will check that square and change some attribute to suggest a hit or a miss. (e.g. x for a miss, # for a hit). If the user scores a hit, then they will go again; otherwise control should pass to the computer o o In Demo mode o o o 4 grids should be displayed, 2 each for the user and computer The first pair of grids should be the same as in Normal mode The 2nd pair of grids should indicate the squares chosen by the user and computer (i.e the squares already played) Play will continue as in Normal mode o

Explanation / Answer

Answer:

Battleship.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.net.*;

public class Battleship extends JFrame
{      
   private static JButton Yes = new JButton("Yes"),
                       done =new JButton("Done");
   private static JFrame namings= new JFrame("namings"),options=new JFrame("Options");
   private static JLabel content, title;
   private static JPanel status_of_data=new JPanel(),opts,medium_of_data;
   private static Container b,c,d;
   private JPanel input;  
   private static JMenuItem m,person_vs_person,person_vs_customer,customer_vs_customer;
   private static String[] given_letters = {" ","A","B","C","D","E","F","G","H","I","J"},
  
               given_numbers = {" ","1","2","3","4","5","6","7","8","9","10"},
  
                   ships = {"Carrier","Battleship","Submarine","Cruiser",
                   "Patrol Boat"},
                   direction = {"Horizontal","Vertical"},
                   level={"Normal", "Hard"},
                   layout={"Manual","Automatic"},
                   colors={"Cyan", "Green", "Yellow", "Magenta", "Pink", "Red",
                   "White"},
                   first={"Player 1", "Player 2", "Random"};
   private JComboBox count_ships_data = new JComboBox(ships),
                   cust_directory = new JComboBox(direction);
   private static JComboBox ultra_level=new JComboBox(level),
                       shipLayout=new JComboBox(layout),
                           Color_of_ship=new JComboBox(colors),
                           runFirst=new JComboBox(first);
                              
   private JTextField menu_bar_of_data = new JTextField();  
   private static int enemy=1,
               i,j,length=5,you=0,
               color_previous=0,
               laterFirst=0,
               old_layout=0,
               old_level=0,
               ready_to_play=0,
               side_index=0,
               duration_index=0;
   private static Player players[]=new Player[2];
   private static JButton task_completed=new JButton("task_completed");
   private static int w=0,a=0,s=0,t=0,e=0;
   private static String[][] hit_of_ship=new String[10][10];
   private static String member,member2;
   private static Color[] color={Color.cyan,Color.green,Color.yellow,Color.magenta,
                                   Color.pink,   Color.red,   Color.white};         
   private static Object selectedValue=" ",
                       gametype;
   private static BattleshipClient me;
   private static boolean game_completed=false;
  
   public Battleship()
   {  
       setTitle("Battleship Game");      
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setJMenuBar(createMenuBar());
       setResizable(false);          
      

       member=JOptionPane.showInputDialog("Enter your name.");      
       int virtual=0;
       while (((member==null)||(member.equals("")))&&(virtual<3))
       {              
           member=JOptionPane.showInputDialog("You have to input something.");
           if ((member!=null)&&(!member.equals("")))
               virtual=4;
           else
               virtual++;
       }
       if (virtual==3)
       {
JOptionPane.showMessageDialog(null,"You are having trouble inputting your name, Thank You.","",JOptionPane.INFORMATION_MESSAGE);
           member="Checkagain";
       }
       players[you]=new Player (member);
       players[enemy]=new Player ("Computer");                      
       b=getContentPane();      
       b.add(attachBoard(you),BorderLayout.CENTER);          
       c=getContentPane();
       d = getContentPane();
       medium_of_data=shipinput();
       d.add(medium_of_data,BorderLayout.NORTH);          
       pack();      
       setVisible(true);
      
   }  
  
   public static boolean getgame_completed()
   {
      return game_completed;  
   }

   public static void setgame_completed(boolean b)
   {
      game_completed=b;  
   }
  
  
   public void whoGoesFirst()
   {
       int x=0;
       if (runFirst.getSelecteduration_index()!=2)
       {
           if (runFirst.getSelecteduration_index()!=you)
               otherthanYou();  
           players[runFirst.getSelecteduration_index()].getTimer().start();
           x=runFirst.getSelecteduration_index();
       }
       else
       {      
           int rand=(int)(Math.random()*2);                  
           JOptionPane.showMessageDialog(null,players[rand].getmember()+" will "
           +"go intially.","",JOptionPane.PLAIN_MESSAGE);
           if (rand!=you)
               otherthanYou();  
           players[rand].getTimer().start();
           x=rand;
       }
       if
       ((!players[x].getmember().equals("Computer"))||(!players[x].getmember().equals("CPU1"))||(!players[x].getmember().equals("CPU2")))
           players[x].setMove(true);
   }
  
  
   public static Color getColor()
   {          
       return (color[Color_of_ship.getSelecteduration_index()]);  
   }
  
  
   public static boolean isLocal()
   {
       if ((gametype==person_vs_person)&&(selectedValue.equals("Local")))
               return true;
       else
           return false;
   }
  
  
   public static void otherthanYou()
   {
       if (you==1)
       {  
           you=0;
           enemy=1;
       }
       else
       {
           you=1;
           enemy=0;
       }  
   }
  
  
   public static boolean isAutoSet()
   {
       if (shipLayout.getSelecteduration_index()==0)
           return false;
       else
           return true;
   }
  
  
  
   public static int getW()
   {
       return w;  
   }
  
  
   public static int getA()
   {
       return a;  
   }

   public static int getS()
   {
       return s;  
   }
  
  
   public static int getT()
   {
       return t;  
   }
  
  
   public static int getE()
   {
       return e;  
   }      
  
   public static int getready_to_play()
   {
       return ready_to_play;  
   }
  
   public static JFrame getnamings()
   {
       return namings;  
   }
  
   public static void setcontent(JLabel x)
   {
       content=x;  
   }
  
   public static JLabel getcontent()
   {
       return content;  
   }
  
   public static JPanel getstatus_of_data()
   {
       return status_of_data;  
   }  
  
   public static void settask_completed(boolean k)
   {
       task_completed.setEnabled(k);  
   }  
  
   public static Player getPlayers(int x)
   {
       return players[x];  
   }
  
   public static String getDirection(int i)
   {
       return direction[i];  
   }
  
   public static String getgiven_letters(int i)
   {
       return given_letters[i];  
   }  
  
   public static String getShips(int i)
   {
       return ships[i];  
   }
  
   public static String getgiven_numbers(int i)
   {
       return given_numbers[i];  
   }  
  
   public static int getside_index()
   {
       return side_index;  
   }
  
   public static int getduration_index()
   {
       return duration_index;  
   }  
  
   public static int getYou()
   {
       return you;  
   }
  
   public static int getEnemy()
   {
       return enemy;  
   }  
  
   public static void setYou(int x)
   {
       you=x;  
   }
  
   public static void setEnemy(int x)
   {
       enemy=x;  
   }
  

   public JMenuBar createMenuBar()
   {
       JMenu menu;
  
  
       JMenuBar menuBar = new JMenuBar();

      
       menu = new JMenu("Game");
       menuBar.add(menu);
       m = new JMenu("New Game");      
       menu.add(m);
      

       GameListener stuff = new GameListener();
       person_vs_person = new JMenuItem("Player vs. Player");      
       person_vs_person.addActionListener(stuff);
       m.add(person_vs_person);
       person_vs_customer = new JMenuItem("Player vs. Computer");
       person_vs_customer.addActionListener(stuff);
       m.add(person_vs_customer);
       customer_vs_customer = new JMenuItem("Computer vs. Computer");
       customer_vs_customer.addActionListener(stuff);
       m.add(customer_vs_customer);
      
       m = new JMenuItem("Rules and Rgulations To Be Followed");
       m.addActionListener(new RulesListener());
       menu.add(m);
       m = new JMenuItem("namings");
       m.addActionListener(new status_of_dataListener());      
       menu.add(m);
       m = new JMenuItem("Options existing Now");
       m.addActionListener(new OptionsListener());      
       menu.add(m);
       m = new JMenuItem("Exit");
       m.addActionListener(new ExitListener());
       menu.add(m);  
       return menuBar;
   }
  
  
   public JPanel shipinput()
   {
       input= new JPanel();
       menu_bar_of_data.setText("Choose a ship and its front position and direction.");
       menu_bar_of_data.setFont(new Font("Message New", Font.BOLD, 14));
       menu_bar_of_data.setEditable(false);
      
       count_ships_data.setSelecteduration_index(0);  
       count_ships_data.addActionListener(new ShipsListener());
       TitledBorder title;
       title = BorderFactory.createTitledBorder("Ships");
       count_ships_data.setBorder(title);  
       input.add(count_ships_data);      
       cust_directory.setSelecteduration_index(0);  
       cust_directory.addActionListener(new DirectListener());  
       input.add(cust_directory);
       title = BorderFactory.createTitledBorder("Direction");
       cust_directory.setBorder(title);      
       task_completed.setEnabled(false);
       task_completed.addActionListener(new task_completedListener());
       input.add(task_completed);
       return input;
   }  
  
  
   public JPanel attachBoard(int n)
   {
       players[n].setMyBoard(new JPanel(new GridLayout(11,11)));  
       JTextField k;      
       for (i=0;i<11;i++)
       {          
           for (j=0;j<11;j++)
           {
               if ((j!=0)&&(i!=0))
               {                  
                   players[n].getBboard(i-1,j-1).addActionListener(new BoardListener());
                   players[n].getMyBoard().add(players[n].getBboard(i-1,j-1));
               }              
               if (i==0)
               {              
                   if (j!=0)
                   {  
                      
                       k= new JTextField(Battleship.getgiven_numbers(j));
                       k.setEditable(false);
                       k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
                   }                                  
                   else
                   {  
                      
                       k= new JTextField();
                       k.setEditable(false);                      
                   }
                   players[n].getMyBoard().add(k);
               }
               else if (j==0)                  
               {  
                   k= new JTextField(Battleship.getgiven_letters(i));  
                   k.setEditable(false);
                   k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
                   players[n].getMyBoard().add(k);
               }              
           }
       }
       return players[n].getMyBoard();      
   }
  
  
   public JPanel automateBoard(int u,int t)
   {
       players[u].setGBoard(new JPanel(new GridLayout(11,11)));  
       JTextField k;  
       if (!players[u].getmember().equals("Unknown"))
           for (i=0;i<5;i++)
           {              
               players[u].setBoats(i,players[u].getBoats(i).compinput(i,u));
           }      
       for (i=0;i<11;i++)
       {          
           for (j=0;j<11;j++)
           {
               if ((j!=0)&&(i!=0))
               {                              
                   if ((players[u].getmember().equals("Computer"))||(isLocal()))                      
                   {                      
                       players[u].getBboard(i-1,j-1).addActionListener(new AttackListener());                                  
                   }                      
                   else if
                       ((players[t].getmember().equals("Computer"))||(players[t].getmember().equals("CPU1"))||(players[t].getmember().equals("CPU2"))||(players[t].getmember().equals("Unknown")))          
                   {
                       if (players[u].getHitOrMiss(i-1,j-1))
                           players[u].setBboard(i-1,j-1,getColor());                      
                   }
                   else
                   {
                       players[u].getBboard(i-1,j-1).addActionListener(new InternetListener());      
                   }
                   players[u].getGBoard().add(players[u].getBboard(i-1,j-1));
               }              
               if (i==0)
               {              
                   if (j!=0)
                   {  
                  
                       k= new JTextField(Battleship.getgiven_numbers(j));
                       k.setEditable(false);
                       k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
                   }                                  
                   else
                   {  
                      
                       k= new JTextField();
                       k.setEditable(false);                      
                   }
                   players[u].getGBoard().add(k);
               }
               else if (j==0)                  
               {  
                   k= new JTextField(Battleship.getgiven_letters(i));  
                   k.setEditable(false);
                   k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
                   players[u].getGBoard().add(k);
               }              
           }          
       }
       return players[u].getGBoard();      
   }
  
  
   private class ShipsListener implements ActionListener
   {  
       public void actionPerformed(ActionEvent v)
       {              
           side_index=count_ships_data.getSelecteduration_index();
           if (players[you].getBoats(side_index)!=null)
               cust_directory.setSelecteduration_index(players[you].getBoats(side_index).getDirect());
           switch (side_index)
           {
               case 0:       length=5;
               break;
               case 1:       length=4;
               break;
               case 2:       length=3;  
               break;
               case 3:       length=3;
               break;
               case 4:       length=2;
               break;                          
           }
           if (players[you].getBoats(side_index) != null)
           {
               Ship boat=new Ship(ships[side_index],players[you].getBoats(side_index).getDirect()
               ,length,players[you].getBoats(side_index).getX(),players[you].getBoats(side_index).getY());      
               players[you].getBoats(side_index).clearship();
               players[you].setBoats(side_index,boat);
               players[you].getBoats(side_index).placeship();          
           }                          
       }
   }          
          
      
   private class DirectListener implements ActionListener
   {  
       public void actionPerformed(ActionEvent v)
       {                      
           duration_index = cust_directory.getSelecteduration_index();                  
           if (players[you].getBoats(side_index) != null)
           {
               Ship boat=new Ship(ships[side_index],duration_index,players[you].getBoats(side_index).getLength(),
              players[you].getBoats(side_index).getX(),players[you].getBoats(side_index).getY());         
               players[you].getBoats(side_index).clearship();
               players[you].setBoats(side_index,boat);
               players[you].getBoats(side_index).placeship();         
           }                      
       }
   }              
  
          
   private class BoardListener implements ActionListener
   {  
       public void actionPerformed(ActionEvent v)
       {              
           if (ready_to_play==0)
           {
               if (players[you].getBoats(side_index)!=null)
                   players[you].getBoats(side_index).clearship();
               Object source = v.getSource();
               outer:                      
               for (i=0;i<10;i++)
               {              
                   for (j=0;j<10;j++)
                   {
                       if (source==players[you].getBboard(i,j))
                       {                      
                           switch (side_index)
                           {
                               case 0:   {                                          
                                           if (w==0)
                                               w++;                                                      
                                       }
                               break;                      
                               case 1:   {                                          
                                           if (a==0)
                                               a++;                                                      
                                       }
                               break;
                               case 2:   {                              
                                           if (s==0)                              
                                               s++;
                                       }
                               break;
                               case 3:   {                                  
                                           if (t==0)
                                               t++;                                                  
                                       }
                           break;
                           case 4:   {                              
                                       if (e==0)
                                           e++;                                                          
                                   }
                           break;                          
                       }  
                       players[you].setBoats(side_index,new Ship(ships[side_index],duration_index,length,i,j));                                                                                                  
                       break outer;                      
                   }                  
               }
           }          
           players[you].getBoats(side_index).placeship();
           }                      
       }
}