Create two java files (client and server). You will need to run two classes simu
ID: 3828074 • 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 E5Explanation / Answer
Answer:
Player.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Player {
DataInputStream Inputdata;
DataOutputStream OutputData;
Socket sock1;
int FiredData;
public Player(Socket s1) throws IOException
{
sock1=s1;
Inputdata=new DataInputStream(s1.getInputStream());
OutputData=new DataOutputStream(s1.getOutputStream());
FiredData=0;
}
public void OptionsendMessage(String message1) throws IOException
{
OutputData.writeUTF(message1);
OutputData.flush();
}
public String MessageReceivers() throws IOException
{
return Inputdata.readUTF();
}
public void disconnectSS() throws IOException
{
OutputData.close();
Inputdata.close();
sock1.close();
}
public void CountIncrement()
{
FiredData++;
}
public int getCount()
{
return FiredData;
}
}
Board.java
import java.util.Random;
public class Board {
char dataGrid[][];
int FiredData;
public Board()
{
dataGrid=new char[5][5];
BoardInitilise();
}
void BoardInitilise()
{
for(int it=0;it<5;it++)
for(int j=0;j<5;j++)
dataGrid[it][j]=' ';
int ctr=0;
Random rd=new Random();
int rows,cols;
while(ctr!=7)
{
rows=rd.nextInt(5);
cols=rd.nextInt(5);
if(dataGrid[rows][cols]=='*')
continue;
else
{
dataGrid[rows][cols]='*';
ctr++;
}
}
FiredData=0;
}
public boolean calcFire(int rows,int cols)
{
if(dataGrid[rows][cols]==' ')
{
dataGrid[rows][cols]='X';
return false;
}
else if(dataGrid[rows][cols]=='*')
{
dataGrid[rows][cols]='S';
FiredData++;
return true;
}
else
{
return false;
}
}
boolean isGameOverS()
{
return FiredData==7;
}
public String toString()
{
char ch1;
StringBuffer bufC=new StringBuffer();
for(int it=0;it<5;it++)
for(int j=0;j<5;j++)
{
ch1=dataGrid[it][j];
if(ch1=='*')
ch1=' ';
bufC.append(ch1);
}
return bufC.toString();
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
Player playersOf[];
ServerSocket server_socketS;
int portD;
public Server(int portNum)
{
portD=portNum;
}
public void start() throws IOException{
server_socketS=new ServerSocket(portD);
System.out.println("Server started on portD "+portD);
playersOf=new Player[2];
Socket s1;
s1=server_socketS.accept();
playersOf[0]=new Player(s1);
playersOf[0].OptionsendMessage("You are Player1. Waiting for Player 2...");
s1=server_socketS.accept();
playersOf[1]=new Player(s1);
playersOf[1].OptionsendMessage("You are Player2.");
String message="Game begins.",location;
System.out.println(message);
playersOf[0].OptionsendMessage(message);
playersOf[1].OptionsendMessage(message);
Board b=new Board();
int turn=0;
while(true)
{
message="Your turn";
playersOf[turn].OptionsendMessage(message);
playersOf[turn].OptionsendMessage("Board:"+b.toString());
location=playersOf[turn].MessageReceivers();
if(updateBoarddd(b, location))
{
playersOf[turn].CountIncrement();
playersOf[turn].OptionsendMessage("It's1 a Hit!");
}
else
{
playersOf[turn].OptionsendMessage("It's1 a Miss!");
}
if(b.isGameOverS())
{
int c1=playersOf[turn].getCount(),c2=playersOf[1-turn].getCount();
if(c1>c2)
{
playersOf[turn].OptionsendMessage("You Win! You hit "+c1+" ships.");
String winner="Player "+(turn==0?"1":"2");
playersOf[1-turn].OptionsendMessage(winner+" Wins! He hit "+c1+" ships.");
}
else
{
String winner="Player "+((1-turn)==0?"1":"2");
playersOf[1-turn].OptionsendMessage("You Win! You hit "+c2+" ships.");
playersOf[turn].OptionsendMessage(winner+" Wins! He hit "+c2+" ships.");
}
break;
}
else
turn=1-turn;
}
message="Exit";
System.out.println(message);
playersOf[0].OptionsendMessage(message);
playersOf[1].OptionsendMessage(message);
disconnectSS();
}
public boolean updateBoarddd(Board boards,String loct)
{
int row=loct.charAt(0)-'A';
int col=loct.charAt(1)-'1';
return boards.calcFire(row, col);
}
public void disconnectSS() throws IOException
{
server_socketS.close();
playersOf[0].disconnectSS();
playersOf[1].disconnectSS();
}
public static void main(String[] args) {
Server ss=new Server(2222);
try {
ss.start();
} catch (IOException e) {
System.out.println("Exception occured: "+e.getMessage());
}
}
}
Client.java
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
Player playerss;
int pp;
public Client()
{
}
private String getLocationss(Scanner ss)
{
String loct;
char rr,cc;
boolean validd;
do
{
System.out.print(" Enter location: ");
loct=ss.next();
if(loct.length()==2)
{
rr=loct.charAt(0);
cc=loct.charAt(1);
if(rr>='A' && rr<='E' && cc>='1' && cc<='5')
validd=true;
else
validd=false;
}
else
validd=false;
if(!validd)
System.out.println("Invalid location!");
}while(!validd);
return loct;
}
public void connect(String host,int pp) throws UnknownHostException, IOException
{
Socket s1=new Socket(host,pp);
playerss=new Player(s1);
Scanner ss=new Scanner(System.in);
String location;
String message;
while(true)
{
message=playerss.MessageReceivers();
if(message.startsWith("Board:"))
{
displayBoard(message);
location=getLocationss(ss);
playerss.OptionsendMessage(location);
}
else if(message.equals("Exit"))
break;
else
System.out.println(message);
}
disconnectSS();
}
public void displayBoard(String message)
{
String board=message.substring(6);
int k=0;
char ch;
for(int i=0;i<5;i++)
{
System.out.print(" | ");
for(int j=0;j<5;j++)
{
ch=board.charAt(k);
System.out.print(ch+" | ");
k++;
}
System.out.print(" _____________________");
}
}
public void disconnectSS() throws IOException
{
System.out.println("Disconnecting from server");
playerss.disconnectSS();
}
public static void main(String[] args) {
Client cc=new Client();
String server="localhost";
if(args.length==2)
server=args[1];
try {
cc.connect(server, 2222);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.