In java Create a data structure that represents a 25X25 grid
In java Create a data structure that represents a 25X25 grid. must be able to use this grid to place the two battleships and to track the progress of searches for battleships.
Solution
import java.util.Random;
import java.util.Scanner;
public class battleshp {
public static void main(String[] args) {
int[][] board = new int[25][25];//25*25 grid
int[][] shps = new int[3][2];
int[] shot = new int[2];//no of shot
int attempts=0,
shotHit=0;
initBoard(board);//function for board
initshps(shps);//function for ships
System.out.println();
do{
showBoard(board);
shot(shot);
attempts++;
if(hit(shot,shps)){ //hit function
hint(shot,shps,attempts);
shotHit++;
}
else
hint(shot,shps,attempts);
changeboard(shot,shps,board);
}while(shotHit!=3);
System.out.println(\"\ \ \ game finished! You hit 3 shps in \"+attempts+\" attempts\");
showBoard(board);
}
public static void initBoard(int[][] board){ //intigerboard
for(int rw=0 ; rw < 25 ; rw++ )
for(int col=0 ; col < 5 ; col++ )
board[rw][col]=-1;
}
public static void showBoard(int[][] board){ //display board
System.out.println(\"\\t1 \\t2 \\t3 \\t4 \\t5\");
System.out.println();
for(int rw=0 ; rw < 25 ; rw++ ){
System.out.print((rw+1)+\"\");
for(int col=0 ; col < 25 ; col++ ){
if(board[rw][col]==-1){
System.out.print(\"\\t\"+\"~\");
}else if(board[rw][col]==0){
System.out.print(\"\\t\"+\"*\");
}else if(board[rw][col]==1){
System.out.print(\"\\t\"+\"X\");
}
}
System.out.println();
}
}
public static void initshps(int[][] shps){
Random random = new Random();
for(int shp=0 ; shp < 3 ; shp++){
shps[shp][0]=random.nextInt(5);
shps[shp][1]=random.nextInt(5);
//let\'s check if that shot was already tried
//if it was, just finish the do...while when a new pair was randomly selected
for(int last=0 ; last < shp ; last++){
if( (shps[shp][0] == shps[last][0])&&(shps[shp][1] == shps[last][1]) )
do{
shps[shp][0]=random.nextInt(5);
shps[shp][1]=random.nextInt(5);
}while( (shps[shp][0] == shps[last][0])&&(shps[shp][1] == shps[last][1]) );
}
}
}
public static void shot(int[] shot){
Scanner input = new Scanner(System.in);
System.out.print(\"rw: \");
shot[0] = input.nextInt();
shot[0]--;
System.out.print(\"col: \");
shot[1] = input.nextInt();
shot[1]--;
}
public static boolean hit(int[] shot, int[][] shps){
for(int shp=0 ; shp<shps.length ; shp++){
if( shot[0]==shps[shp][0] && shot[1]==shps[shp][1]){
System.out.printf(\"You hit a shp located in (%d,%d)\ \",shot[0]+1,shot[1]+1);
return true;
}
}
return false;
}
public static void hint(int[] shot, int[][] shps, int attempt){
int rw=0,
col=0;
for(int line=0 ; line < shps.length ; line++){
if(shps[line][0]==shot[0])
rw++;
if(shps[line][1]==shot[1])
col++;
}
System.out.printf(\"\ Hint %d: \ rw %d -> %d shps\ \" +
\"col%d -> %d shps\ \",attempt,shot[0]+1,rw,shot[1]+1,col);
}
public static void changeboard(int[] shot, int[][] shps, int[][] board){
if(hit(shot,shps))
board[shot[0]][shot[1]]=1;
else
board[shot[0]][shot[1]]=0;
}
}