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

For this assigment, you will submit TWO AND ONLY TWO .java files. (SERVER, CLIEN

ID: 3831852 • Letter: F

Question

For this assigment, you will submit TWO AND ONLY TWO .java files. (SERVER, CLIENT) You will need to run two classes simultaneously for this activity. Make sure you have a compiler that is capable of this.

For the for a previus exercise, we looked at how a Server/Client program can operate an online store. Now we’re going to look at another industry for these kinds of programs: gaming. For this project, we’re going to build a game that can be played with two players.

The name of the game is BattleShip. Classically, the nature of the game is having two players construct a small fleet of ships in a grid and then try to sink the opponent’s. For this project however, we’re going to modify the rules for simplicity. Here’s how it will work – the Server will start off by creating a 5x5 grid in which it will randomly place 7 ships (each taking up a single tile in the grid). Then, players will take turns choosing grid tiles at which to fire. If they hit one of the Server’s ships, that player scores a point. Then the next player goes. This continues until all 7 ships have been hit by either player. The player with the most points wins, then the Server disconnects.

The guidelines are as follows:

Both players should be running the same Client class. Each player should have their own console. This can be done by running the same Client class twice, each with a single Socket to connect to the Server.

The Server should accept both players’ connections before setting up the game. The Server should assign the users as Player 1 and Player 2.

The Server should keep track of the board and the score of both players. The ships should be randomly placed on the board after both players connect.

Players should take turns. While it is not the player’s turn, the console should inform the player that they’re waiting on the other player.

The grid layout should be as follows:

When the player’s turn begins, they should be shown a visual representation of the current state of the board, including which spots have been hit and which ones have not. In addition, this board should show where ships that have been hit were. Hint: create a String from the board and send that instead of sending the whole board.

The player should be asked to input a grid coordinate in the format ‘A1’ – always 2 characters with the first being a letter (capital or lowercase) A-E and the second should be an integer 1-5. Data validation should be done on the input to make sure the user’s entry follows this format. If it does not, an invalid entry prompt should be shown and the player should be asked to re-enter.

Data Validation for valid entries should be performed on the Client-side.

Once an entry has been confirmed as valid, it should be sent to the Server and the grid should be updated for the player’s move.

When a player has chosen a move and the board has been updated, both players should receive a message detailing whether the move was a hit or a miss.

Once the message has been sent, the Server should allow the other player to take their turn in the same manner.

Once all 7 ships have been hit, the Server should finish the current player’s turn and then end the game. The final scores should then be displayed to both players, along with a short message telling both players which one won.

Important Things to Note:

Due to the turn-based nature of this program, I highly suggest not using Threads for this application. This program can be done much easier in a linear structure.

No GUI applications are allowed for this program. Your submission must be console-based.

Your program must include data validation for any input. In the case that invalid data is entered, the user must be told to re-enter without throwing an exception.

Send regular messages to the server’s console. At the very least, send a message when the server connects, when either Client connects, when input is received from the client, and when the server disconnects.

Make sure that in the natural runtime of your program when the server is disconnected that all sockets, scanners, and any other form of I/O is closed – leaving these open can cause a security leak that, while harmless on a localhost, can be dangerous on other IPs.

Leave documentation and comments in your code to explain things step-by-step. This is just good practice. It doesn’t have to be a lot; just enough to explain your process in a simple way.

User-Friendliness is important! Make sure your program looks good on the user’s end.

Connectivity

8 points

The server opens a port on a localhost, and the clients successfully connect. The program keeps the connection open during RunTime and successfully closes it when the program is finished.

User-Input

4 points

The client program successfully obtains user-input, and data validation is done correctly to validate the input obtained. The user is asked for new input if invalid input is given.

User-Friendliness

4 points

The look-and-feel of the program runs well; the client sends good user-friendly output; the server relays information to the console.

App Reliability

6 points

The program correctly sends the user input to the server when necessary; the server correctly sends information to the user; all information sent and received is correct.

Good Practice

2 points

No dead code; no unused imports or variables, IO and Sockets are correctly closed. Good documentation.

Total

24 points

A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 C4 C5 D1 D2 D3 D4 D5 E1 E2 E3 E4 E5

Explanation / Answer

Client.java:

import java.io.*;

import java.net.*;

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

public class BattleshipClient {   
  
   int i,j,x,y,endp;
   boolean gameover=false;
   String servername=" ";
   String start=" ";
   Socket batshipSocket = null;
   PrintWriter out = null;
   BufferedReader in = null;
      
   public BattleshipClient () throws IOException {
      
       int i,j;
      
       try {
           servername=JOptionPane.showInputDialog(null,"Input the name of"
           +" the server you wish to connect to. )",
           "Server Name",JOptionPane.PLAIN_MESSAGE);
           if (servername==null)
               servername=" ";
           System.out.println("Server Name: "+servername);
bsSocket = new Socket(servername, 4444);
this.out = new PrintWriter(batshipsSocket.getOutputStream(), true);
this.in = new BufferedReader(new InputStreamReader(batshipSocket.getInputStream()));
          
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null,"Don't know about host: "
           +servername+".","Error",JOptionPane.WARNING_MESSAGE);
           servername="invalid";
} catch (IOException e) {
           JOptionPane.showMessageDialog(null,"Couldn't get I/O for the connec"
           +"tion to: "+servername+".","Error",JOptionPane.WARNING_MESSAGE);
           servername="invalid";   
}  
}
  
   public void listen() throws IOException
   {      
       while(!(start=this.in.readLine()).equals("play"))
       {          
           System.out.println("start ="+start);
           if (start.equals("getmove"))
               break;
           else if (start.equals("opponent"))
           {
               Battleship.getPlayers(1).setUser(in.readLine());  
           }              
           System.out.println("I'm still in the loop man.");
       }
       if (!start.equals("getmove"))          
       {
           Battleship.getPlayers(0).setMove(true);
           JOptionPane.showMessageDialog(null,Battleship.getPlayers(0).getUser()
           +" move.","",JOptionPane.INFORMATION_MESSAGE);
       }
      
   }  
  
   public void results()
   {
       String results=null;
      
       try
       {
           while(!(results=in.readLine()).equals("results"))
           {  
              
           }
           results=in.readLine();
           System.out.println("results: "+results);          
       }
       catch (IOException e){ System.out.println("Nothing's there.");
       }
       if (results.startsWith("miss"))
       {
           Battleship.getPlayers(1).setBboard(x,y,Color.blue);
           Battleship.getPlayers(0).setShots();
       }
       else if (results.startsWith("hit"))
       {
           Battleship.getPlayers(0).setHits();          
           results=results.substring(results.indexOf(" ")+1);          
           if (results.startsWith("shipsunk"))
           {
               Battleship.getPlayers(1).setShipsLeft();
               results=results.substring(results.indexOf(" ")+1);
               if (!results.startsWith("Patrol"))
                   JOptionPane.showMessageDialog(null,"You sank the "+
                   results.substring(0,results.indexOf(" "))+"!","Good Job!",              
                   JOptionPane.INFORMATION_MESSAGE);
               else
               {
                   JOptionPane.showMessageDialog(null,"You sank the Patrol Boa"
                   +"t!","Good Job!",              
                   JOptionPane.INFORMATION_MESSAGE);
                   results=results.substring(results.indexOf(" ")+1);
               }
               results=results.substring(results.indexOf(" ")+1);
               x=Integer.parseInt(results.substring(0,1));
               y=Integer.parseInt(results.substring(2,3));
               endp=Integer.parseInt(results.substring(6,7));              
               if (Integer.parseInt(results.substring(4,5))==0)
               {                  
                   for (i=x;i<=endp;i++)
                   {
                       Battleship.getPlayers(1).setBboard(i,y,Color.black);
                   }
               }
               else
               {
                   for (i=y;i<=endp;i++)
                   {
                       Battleship.getPlayers(1).setBboard(x,i,Color.black);
                   }                  
               }
           }          
           else
           {          
               Battleship.getPlayers(1).setBboard(x,y,Color.orange);
           }
           Battleship.getPlayers(0).setShots();          
       }
       else if (results.startsWith("theirshot"))
       {
           results=results.substring(results.indexOf(" ")+1);
           System.out.println("results: "+results);
           x=Integer.parseInt(results.substring(0,1));
           y=Integer.parseInt(results.substring(2,3));
           if (!Battleship.getPlayers(0).getWhatShip(x,y).equals(" "))
           {
               Battleship.getPlayers(1).setHits();
               if (!Battleship.getPlayers(0).isSunk(x,y
                   ,Battleship.getPlayers(0).getWhatShip(x,y)))
                   Battleship.getPlayers(0).setBboard(x,y,Color.orange);
           }
           else
           Battleship.getPlayers(0).setBboard(x,y,Color.blue);
           Battleship.getPlayers(1).setShots();              
       }
       else if (results.startsWith("wastedturn"))
       {          
          
       }      
       else if (results.startsWith("lostturn"))
       {
           JOptionPane.showMessageDialog(null,"You took too long!",
           "Lost Turn",JOptionPane.INFORMATION_MESSAGE);              
       }  
       try
       {
       if (in.readLine().equals("gameover"))
       {
               Battleship.setGameOver(true);
               if (Battleship.getPlayers(0).getShipsLeft()!=0)
                   JOptionPane.showMessageDialog(null,"YOU WON!",
                   "It's A Celebration!",JOptionPane.INFORMATION_MESSAGE);
               else
                   JOptionPane.showMessageDialog(null,"You Lost",
                   "Sorry!",JOptionPane.INFORMATION_MESSAGE);
       }
       }
       catch (IOException g){}
       Player.isStatsOpen();  
      
       System.out.println("results received");      
   }
  
   public String getServerName()
   {
       return servername;  
   }
      
   public void fireShot(int a, int b)
   {
       x=a;
       y=b;      
       out.println(x);
       out.println(y);
       System.out.println("shot fired: "+Battleship.getCletters(x+1)+","+Battleship.getCnumbers(y+1));      
   }
  
   public void fireShot()
   {
       out.println("wastedturn");      
   }
  
   public void sendShips()
   {      
       out.println(Battleship.getPlayers(Battleship.getYou()).getUser());          
       for (i=0;i<10;i++)
           for (j=0;j<10;j++)
               out.println(Battleship.getPlayers(Battleship.getYou()).getWhatShip(i,j));      
   }
}

Server.java:

import java.net.*;
import java.io.*;
import java.util.Vector;

public class BattleshipServer
{  
   private static BattleshipProtocol p;
   private static Socket sockets=null;
      
   public static void main(String[] args) throws IOException
   {
       boolean gameover=false;
        int i,j, num = 0;
       ServerSocket serverSocket = null;  
       Vector threads=new Vector();      
     
      try {
serverSocket = new ServerSocket(4444);
}
       catch (IOException e)
       {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}   
       while (num!=2)
       {
           if (num==0)
           {
               sockets=serverSocket.accept();              
               threads.add(new BattleshipThread(sockets));
               System.out.println(num);
               ((Thread)threads.elementAt(num)).start();              
           }
           else
           {
               sockets=serverSocket.accept();              
               threads.add(new BattleshipThread(sockets));
               System.out.println(num);
               ((Thread)threads.elementAt(num)).start();                  
           }
      
           num++;          
       }
       ((BattleshipThread)threads.elementAt(num-2)).sendMessage("opponent");
       ((BattleshipThread)threads.elementAt(num-2)).sendMessage(((BattleshipThread)threads.elementAt(num-1)).getMyName());
       ((BattleshipThread)threads.elementAt(num-1)).sendMessage("opponent");
       ((BattleshipThread)threads.elementAt(num-1)).sendMessage(((BattleshipThread)threads.elementAt(num-2)).getMyName());
       p=new BattleshipProtocol(((BattleshipThread)threads.elementAt(num-2))
           ,((BattleshipThread)threads.elementAt(num-1)));  
       while (!gameover)
       {
           gameover=p.play();          
       }          
   }     
     
   public static BattleshipProtocol getProtocol()
   {
       return p;     
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote