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

Create two java files (client and server). You will need to run two classes simu

ID: 3829340 • Letter: C

Question

Create two java files (client and server). You will need to run two classes simultaneously for this activity. Make sure you have a compiler that is capable of this.

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.

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

Find the below code for the above problem statement

The architecture is divided in to the two below package and one is client and the other is server

Client packages comes in to two classes:

ClientConnect.Java

board.java

Have a look at the below code for ClientConnect.java

***************


import java.io.*;
import java.net.*;

public class ClientConnect {
  
   public static void main(String argv[]) throws Exception
   {
      
       String ip = "127.0.0.1";
       String sentence;
       String modifiedSentence;
       Socket clientSocket;
       Socket hitOrMiss;
       String miss = "miss";
       String hit = "hit";
      
      
       //from command line
       BufferedReader inFromUser = new BufferedReader(
               new InputStreamReader(System.in));
      
       //create the board
      
       board gameBoard = new board();
       //player is asked to add the ships to the board
       System.out.println("Below you can input where you want to" +
               " place your battleships. Please enter them in integers" +
               " starting with the row followed by columns (for example" +
               " start with the head as 11 for row 1, column 1 and " +
               " tail as 51 for row 5 and column 1) Please input the data " +
               "left to right and top to bottom" +
               "Type q when done.");
       while(true){
           System.out.println("Please enter head location:");
           String line1 = inFromUser.readLine();
           System.out.println("Please enter tail location:");
           String line2 = inFromUser.readLine();
           if(!line1.equals("q") || !line2.equals("q")){
               int head = Integer.parseInt(line1);
               int tail = Integer.parseInt(line2);
               //we call the testPos method to verify that we can place
               //the battleship at the inputed locations
               gameBoard.testPos(head, tail);
               if(gameBoard.boatBool == true){
                   gameBoard.createBoat(head, tail);
                   System.out.println("Creating boat at "+head+ " and "+tail);
               }
               else
                   System.out.println("Sorry, can't place the battleship using these locations.");
           }
           else
               break;
       }
      
       gameBoard.printBoard();
      
       ////////////////////////////////////
       //game starts
       ////////////////////////////////////
       clientSocket = new Socket(ip, 6789);
       //from server  
       BufferedReader inFromServer = new BufferedReader(
               new InputStreamReader(clientSocket.getInputStream()));
       //out to server the hit or miss message
       DataOutputStream outToServer = new DataOutputStream(
               clientSocket.getOutputStream());
      
       while(true){
           int hitRow;
           int hitCol;
           //the client sends a hit
           sentence = inFromUser.readLine();
           outToServer.writeBytes(sentence+" ");
           outToServer.flush();
           //the client receives a hit from the server
           modifiedSentence = inFromServer.readLine();
           System.out.println("Result from server: " + modifiedSentence);
          
           modifiedSentence = inFromServer.readLine();
           System.out.println("Hit from server: " + modifiedSentence);
           int clientInt = Integer.parseInt(modifiedSentence);
           hitRow = Math.abs(clientInt/10)-1;
           hitCol = clientInt%10-1;
          
           if(gameBoard.testHit(hitRow, hitCol)){
               gameBoard.testLoss();
               if(gameBoard.testLoss() == false){
                   hit = miss = "You won!";
                   System.out.println("Sorry, you lost!");
               }
               outToServer.writeBytes(hit+" ");
               outToServer.flush();
           }
           else{
               outToServer.writeBytes(miss+" ");
               outToServer.flush();
           }
       }
      
   }
  
}

*****************

board.java


public class board {
   public int[][] board;
   //this will hold info if the boat can be created
   public boolean boatBool;
   public boolean loss = true;
   public String str;
   public board(){
       board = new int[10][10];
   }
   public void testPos(int a, int b){
       int row1 = Math.abs(a/10);
       int col1 = a%10;
       int row2 = Math.abs(b/10);
       int col2 = b%10;
       if(row1 == row2 || col1 == col2){
           boatBool = true;
       }
       else
           boatBool = false;
   }
   //we create a boat
   public void createBoat(int a, int b){
       //we also need to test for the existence of other boats
      
       //create the head and tail of the ship
       int row1 = Math.abs(a/10);
       int col1 = a%10;
       int row2 = Math.abs(b/10);
       int col2 = b%10;
       //testing to see if they are on the same column or row
       //this way we know how to put the ship in the array
       if(row1 == row2){
           //if the boat is on the same row we have to fill the
           //columns out
           for(int i = col1; i<=col2; i++){
               board[row1-1][i-1] = 1;
           }
       }
       else if(col1 == col2){
           for(int i = row1; i<=row2; i++){
               board[i-1][col1-1] = 1;
           }
       }
       else{
           boatBool = false;
       }
   }
   //printing the board
   public void printBoard(){
       for(int i = 0; i<board.length; i++){
           for(int c = 0; c<board[i].length; c++){
               System.out.print(board[i][c]+" ");
           }
           System.out.println();
       }
   }
   public boolean testHit(int row, int col){
       if(board[row][col] == 1){
           board[row][col] = 5;
           printBoard();
           return true;
       }
       else
           return false;
   }
   //test for loss, when all the board is 0's again
   public boolean testLoss(){
       int count = 0;
       boolean bool1 = true;
       for(int i = 0; i<board.length; i++){
           for(int c = 0; c<board[i].length; c++){
               if(board[i][c]==0 || board[i][c]==5){
                   count++;
               }              
           }
       }
       if(count == 100)
           bool1 = false;
       return bool1;
   }
}

****************

Now at the second stage you can go with the server package

The server package will come in the two below classes

TCPserver.java and board.java

Have a look at the below code

TCPServer.java

**************


import java.io.*;
import java.net.*;
public class TCPServer {

   /**
   * @param args
   */
   public static void main(String[] args) throws Exception{
       // TODO Auto-generated method stub
       String clientSentence;
       String serverSentence;
       ServerSocket welcomeSocket;
       Socket serverSocket;
      
       String miss = "miss";
       String hit = "hit";
       String won = "won";
       boolean turn = true;
      
      
       //from command line
       BufferedReader inFromUser = new BufferedReader(
               new InputStreamReader(System.in));
       //create the board
      
       board gameBoard = new board();
      
       //player is asked to add the ships to the board
       System.out.println("Below you can input where you want to" +
               " place your battleships. Please enter them in integers" +
               " starting with the row followed by columns (for example" +
               " start with the head as 11 for row 1, column 1 and " +
               " tail as 51 for row 5 and column 1) . Please input the data " +
               "left to right and top to bottom " +
               "Type q when done.");
       while(true){
           System.out.println("Please enter head location:");
           String line1 = inFromUser.readLine();
           System.out.println("Please enter tail location:");
           String line2 = inFromUser.readLine();
           if(!line1.equals("q") || !line2.equals("q")){
               int head = Integer.parseInt(line1);
               int tail = Integer.parseInt(line2);
               //we call the testPos method to verify that we can place
               //the battleship at the inputed locations
               gameBoard.testPos(head, tail);
               if(gameBoard.boatBool == true){
                   gameBoard.createBoat(head, tail);
                   System.out.println("Creating boat at "+head+ " and "+tail);
               }
               else
                   System.out.println("Sorry, can't place the battleship using these locations.");
           }
           else
               break;
       }
      
       gameBoard.printBoard();
       ////////////////////////////////////
       //game starts
       ////////////////////////////////////
       welcomeSocket = new ServerSocket(6789);
       serverSocket = welcomeSocket.accept();
       //from client
       BufferedReader inFromClient = new BufferedReader(
               new InputStreamReader(serverSocket.getInputStream()));
      
       //out to client the hit or miss message
       DataOutputStream outToClient1 =
           new DataOutputStream(serverSocket.getOutputStream());
      
      
       while(true){
           int hitRow;
           int hitCol;
          
           //the server receives a hit from the client
           //and replies with a hit or miss
           clientSentence = inFromClient.readLine();
           System.out.println("Hit from client: " + clientSentence);
           int clientInt = Integer.parseInt(clientSentence);
           hitRow = Math.abs(clientInt/10)-1;
           hitCol = clientInt%10-1;
          
           if(gameBoard.testHit(hitRow, hitCol)){
               gameBoard.testLoss();
               if(gameBoard.testLoss() == false){
                   hit = miss = "You won!";
                   System.out.println("Sorry, you lost!");
               }
               outToClient1.writeBytes(hit+" ");
               outToClient1.flush();
           }
           else{
               outToClient1.writeBytes(miss+" ");
               outToClient1.flush();
           }
          
           //the server sends a hit
           String newS = inFromUser.readLine();
           outToClient1.writeBytes(newS+" ");
           outToClient1.flush();
          
           clientSentence = inFromClient.readLine();
           System.out.println("Result from client: " + clientSentence);
          
       }
   }

}

*************

Board.java


public class board {
   public int[][] board;
   //this will hold info if the boat can be created
   public boolean boatBool;
   public boolean loss = true;
   public String str;
   public board(){
       board = new int[10][10];
   }
   public void testPos(int a, int b){
       int row1 = Math.abs(a/10);
       int col1 = a%10;
       int row2 = Math.abs(b/10);
       int col2 = b%10;
       if(row1 == row2 || col1 == col2){
           boatBool = true;
       }
       else
           boatBool = false;
   }
   //we create a boat
   public void createBoat(int a, int b){
       //we also need to test for the existence of other boats
      
       //create the head and tail of the ship
       int row1 = Math.abs(a/10);
       int col1 = a%10;
       int row2 = Math.abs(b/10);
       int col2 = b%10;
       //testing to see if they are on the same column or row
       //this way we know how to put the ship in the array
       if(row1 == row2){
           //if the boat is on the same row we have to fill the
           //columns out
           for(int i = col1; i<=col2; i++){
               board[row1-1][i-1] = 1;
           }
       }
       else if(col1 == col2){
           for(int i = row1; i<=row2; i++){
               board[i-1][col1-1] = 1;
           }
       }
       else{
           boatBool = false;
       }
   }
   //printing the board
   public void printBoard(){
       for(int i = 0; i<board.length; i++){
           for(int c = 0; c<board[i].length; c++){
               System.out.print(board[i][c]+" ");
           }
           System.out.println();
       }
   }
   public boolean testHit(int row, int col){
       if(board[row][col] == 1){
           board[row][col] = 5;
           printBoard();
           return true;
       }
       else
           return false;
   }
   //test for loss, when all the board is 0's again
   public boolean testLoss(){
       int count = 0;
       boolean bool1 = true;
       for(int i = 0; i<board.length; i++){
           for(int c = 0; c<board[i].length; c++){
               if(board[i][c]==0 || board[i][c]==5){
                   count++;
               }              
           }
       }
       if(count == 100)
           bool1 = false;
       return bool1;
   }
}

************************

**************

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