SlideShare a Scribd company logo
1 of 9
Download to read offline
Write a program in java in which you will build the“Sink theShipsGame”. The Game has a8 x 8
grid and threeships. Each ship takes up exactly three cells. In the game, it’s you against
thecomputer, but unlike the real battleship game, you don’t place any ships on yourown. Instead,
your job is to sink the computer’s ship in the fewest number of guess.
Goal:Sink all the computer’s ships(three in this case)in the fewest number ofguesses. You’re
given a rating or level, based on how well you perform.Setup:When the game program is
launched, the computerplaces three ships on a8x 8 grid(for an example, see the figure
below).The ships can be placed eithervertically or horizontally (no other placement is valid)on
empty cells of the grid.When that’scomplete the game asks for your first guess.
The computer will prompt you to enter a guess(a cell), that you will type at the command-line as
“1 3”(where “1 3” means 3rdcell ofthe 1strow), “45”, etc.. In response to your guess, you will
see a result at thecommand line,either “Hit”, “Miss”, “Kill” (or whatever the lucky battleship of
the dayis!). When you have sank all three battleships, the game ends by printing out your rating.
Here is a sample run of the game:
Your goal is to sink three ships.
Battleship1, Battleship2, Battleship3
Try to sink them all in the fewest number of guesses
Enter a guess [row (1 to 8)] [col (1 to 8)]: 1 3
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 2 1
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 2 2
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 1
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 1
kill
Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 3
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 1 7
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 3
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 4
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 5
kill
Enter a guess [row (1 to 8)] [col (1 to 8)]: 5 1
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 1
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 6 1
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 61 1
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 6 1
miss
Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 4
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 5
hit
Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 6
kill
All Ships are sank!
It only took you 18 guesses.
You got out before your options sank.
When player can finish the game within 20 guesses, print the following message
(where xx is the number of guesses):
All Ships are sank!
It only took you XX guesses.
You got out before your options sank.
If it takes more than 20 guesses, print the following message
All Ships are sank!
Took you long enough. XX guesses.
Fish are dancing with your options.
The java program should terminate after 25 guesses and it should reveal the
positions of the ships and their status.
Solution
Please follow the code and comments for description :
CODE :
import java.util.Random; // required imports for the code
import java.util.Scanner;
public class SinktheShipsGame { // class to run the code
public static void main(String[] args) { // driver method
int[][] board = new int[8][8]; // required initialisations
int[][] ships = new int[3][2];
int[] shoot = new int[2];
int guesses = 0, shotHit = 0;
boardPlacement(board); // calling the method to print the initial board
shipsPlacement(ships); // method to print the ships and their repsective placements
System.out.println();
do {
showTheBoard(board); // print the board to console
shoot(shoot); // checking the shot from the user
guesses++; // incrementing the guesses
if (hit(shoot, ships)) { // checking the shot given by the user
System.out.printf("You hit a ship.! "); // print the result
shotHit++; // incrementing the shot hits
} else {
System.out.printf("You Missed a ship.! ");
//hint(shoot, ships, guesses);
}
changeTheBoard(shoot, ships, board); // updating the board with the present rsult
if(guesses >= 25) { // checking for the guess count
break; // breaking the loop if is greater than 25
}
} while (shotHit != 3); // iterating the loop till all the 3 ships are shot
if(guesses < 20){ // print the result based on the guess count
System.out.println("   All Ships are sank! It only took you " + guesses + " guesses. You got
out before your options sank.");
} else if (guesses >= 20) {
System.out.println("   All Ships are sank! Took You Long Enough. " + guesses + "
guesses. Fish are dancing with your options.");
} else if (guesses > 25) {
System.out.println("You Lost.! The Result is : ");
showTheBoard(board);
}
}
public static void boardPlacement(int[][] board) { // method to place the board and the results
cells
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
board[row][column] = -1; // returns the desired values
}
}
}
public static void showTheBoard(int[][] board) { // method to shoe the initial or the resultant
board
System.out.println(" t1 t2 t3 t4 t5 t6 t7 t8");
System.out.println();
for (int row = 0; row < 8; row++) { // iterating over the rows and columns
System.out.print((row + 1) + "");
for (int column = 0; column < 8; column++) {
if (board[row][column] == -1) {
System.out.print("t" + "~"); // print the respective results
} else if (board[row][column] == 0) {
System.out.print("t" + "*");
} else if (board[row][column] == 1) {
System.out.print("t" + "X");
}
}
System.out.println();
}
}
public static void shipsPlacement(int[][] ships) { // initial placement of the ships
Random random = new Random();
for (int ship = 0; ship < 3; ship++) { // iterating over the ships count
ships[ship][0] = random.nextInt(8); // getting the random numnber for the cell value
ships[ship][1] = random.nextInt(8);
for (int last = 0; last < ship; last++) { // checking for the last placement of the cell
if ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1])) {
do {
ships[ship][0] = random.nextInt(8);
ships[ship][1] = random.nextInt(8);
} while ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1]));
}
}
}
}
public static void shoot(int[] shoot) { // method that checks and updates the shoot value
Scanner input = new Scanner(System.in);
System.out.printf("Enter a guess [row (1 to 8)] [col (1 to 8)] : ");
shoot[0] = input.nextInt(); // getting the values form the user
shoot[0]--;
shoot[1] = input.nextInt();
shoot[1]--;
}
public static boolean hit(int[] shoot, int[][] ships) { // checking the method to see if the hit is a
success or not
for (int ship = 0; ship < ships.length; ship++) {
if (shoot[0] == ships[ship][0] && shoot[1] == ships[ship][1]) {
return true;
}
}
return false;
}
public static void changeTheBoard(int[] shoot, int[][] ships, int[][] board) { // method that
changes the board
if (hit(shoot, ships)) {
board[shoot[0]][shoot[1]] = 1; // updating the values
} else {
board[shoot[0]][shoot[1]] = 0;
}
}
}
OUTPUT :
1 2 3 4 5 6 7 8
1 ~ ~ ~ ~ ~ ~ ~ ~
2 ~ ~ ~ ~ ~ ~ ~ ~
3 ~ ~ ~ ~ ~ ~ ~ ~
4 ~ ~ ~ ~ ~ ~ ~ ~
5 ~ ~ ~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 ~ ~ ~ ~
5 ~ ~ ~ ~ * ~ ~ ~
6 ~ ~ ~ ~ ~ ~ ~ ~
7 ~ ~ ~ ~ ~ ~ * ~
8 ~ ~ ~ ~ ~ ~ ~ ~
Enter a guess [row (1 to 8)] [col (1 to 8)] : 4
5
You hit a ship.!
1 2 3 4 5 6 7 8
1 * ~ ~ ~ ~ ~ ~ ~
2 ~ ~ ~ ~ ~ ~ ~ ~
3 X ~ ~ ~ ~ ~ ~ ~
4 ~ ~ ~ ~ X ~ ~ ~
5 ~ ~ ~ ~ * ~ ~ ~
6 ~ ~ ~ ~ ~ ~ ~ ~
7 ~ ~ ~ ~ ~ ~ * ~
8 ~ ~ ~ ~ ~ ~ ~ ~
Enter a guess [row (1 to 8)] [col (1 to 8)] : 3
8
You Missed a ship.!
1 2 3 4 5 6 7 8
1 * ~ ~ ~ ~ ~ ~ ~
2 ~ ~ ~ ~ ~ ~ ~ ~
3 X ~ ~ ~ ~ ~ ~ *
4 ~ ~ ~ ~ X ~ ~ ~
5 ~ ~ ~ ~ * ~ ~ ~
6 ~ ~ ~ ~ ~ ~ ~ ~
7 ~ ~ ~ ~ ~ ~ * ~
8 ~ ~ ~ ~ ~ ~ ~ ~
Enter a guess [row (1 to 8)] [col (1 to 8)] : 1
1
You Missed a ship.!
1 2 3 4 5 6 7 8
1 * ~ ~ ~ ~ ~ ~ ~
2 ~ ~ ~ ~ ~ ~ ~ ~
3 X ~ ~ ~ ~ ~ ~ *
4 ~ ~ ~ ~ X ~ ~ ~
5 ~ ~ ~ ~ * ~ ~ ~
6 ~ ~ ~ ~ ~ ~ ~ ~
7 ~ ~ ~ ~ ~ ~ * ~
8 ~ ~ ~ ~ ~ ~ ~ ~
Enter a guess [row (1 to 8)] [col (1 to 8)] : 6
6
You hit a ship.!
All Ships are sank!
It only took you 8 guesses.
You got out before your options sank.
Hope this is helpful.

More Related Content

Similar to Write a program in java in which you will build the“Sink theShipsGam.pdf

import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdf
ADITIEYEWEAR
 
The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdf
eyelineoptics
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
anithareadymade
 
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdfC# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
fazalenterprises
 
i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docx
ursabrooks36447
 
implemement the game.cpp by the header file given. And create main.c.pdf
implemement the game.cpp by the header file given. And create main.c.pdfimplemement the game.cpp by the header file given. And create main.c.pdf
implemement the game.cpp by the header file given. And create main.c.pdf
fazilfootsteps
 
Create a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdfCreate a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdf
arihantsherwani
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
PiersRCoThomsonw
 

Similar to Write a program in java in which you will build the“Sink theShipsGam.pdf (17)

import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdf
 
The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdfC# using Visual studio - Windows Form. If possible step-by-step inst.pdf
C# using Visual studio - Windows Form. If possible step-by-step inst.pdf
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
Basics
BasicsBasics
Basics
 
i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docx
 
implemement the game.cpp by the header file given. And create main.c.pdf
implemement the game.cpp by the header file given. And create main.c.pdfimplemement the game.cpp by the header file given. And create main.c.pdf
implemement the game.cpp by the header file given. And create main.c.pdf
 
Tic tac toe on c++ project
Tic tac toe on c++ projectTic tac toe on c++ project
Tic tac toe on c++ project
 
Quiz using C++
Quiz using C++Quiz using C++
Quiz using C++
 
Python programming lab14
Python programming lab14Python programming lab14
Python programming lab14
 
Create a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdfCreate a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdf
 
[SI] Ada Lovelace Day 2014 - Tampon Run
[SI] Ada Lovelace Day 2014  - Tampon Run[SI] Ada Lovelace Day 2014  - Tampon Run
[SI] Ada Lovelace Day 2014 - Tampon Run
 
Lisp and prolog in artificial intelligence
Lisp and prolog in artificial intelligenceLisp and prolog in artificial intelligence
Lisp and prolog in artificial intelligence
 
Knit One, Compute One - YOW! 2016
Knit One, Compute One - YOW! 2016Knit One, Compute One - YOW! 2016
Knit One, Compute One - YOW! 2016
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding class
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
 

More from archanenterprises

Is fat soluble produced in the skin Vitamin K Cortisol Vitamin A V.pdf
Is fat soluble produced in the skin  Vitamin K Cortisol Vitamin A V.pdfIs fat soluble produced in the skin  Vitamin K Cortisol Vitamin A V.pdf
Is fat soluble produced in the skin Vitamin K Cortisol Vitamin A V.pdf
archanenterprises
 
How exactly do Protease inhibitors help HIV patients fight the disea.pdf
How exactly do Protease inhibitors help HIV patients fight the disea.pdfHow exactly do Protease inhibitors help HIV patients fight the disea.pdf
How exactly do Protease inhibitors help HIV patients fight the disea.pdf
archanenterprises
 
Explain the various categories of ratio analysis and provide example.pdf
Explain the various categories of ratio analysis and provide example.pdfExplain the various categories of ratio analysis and provide example.pdf
Explain the various categories of ratio analysis and provide example.pdf
archanenterprises
 
Briefly explain the ventral and dorsal body cavities and the membran.pdf
Briefly explain the ventral and dorsal body cavities and the membran.pdfBriefly explain the ventral and dorsal body cavities and the membran.pdf
Briefly explain the ventral and dorsal body cavities and the membran.pdf
archanenterprises
 
Write a 250-300 word abstract explaining that the internet is the gr.pdf
Write a 250-300 word abstract explaining that the internet is the gr.pdfWrite a 250-300 word abstract explaining that the internet is the gr.pdf
Write a 250-300 word abstract explaining that the internet is the gr.pdf
archanenterprises
 
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdf
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdfWhy is it recommended that vegans take an oral vitamin B12 supplemen.pdf
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdf
archanenterprises
 

More from archanenterprises (20)

Lists the stages in the development of the earth and the formatio.pdf
Lists the stages in the development of the earth and the formatio.pdfLists the stages in the development of the earth and the formatio.pdf
Lists the stages in the development of the earth and the formatio.pdf
 
Martinez Company had 210,000 shares of common stock outstanding on D.pdf
Martinez Company had 210,000 shares of common stock outstanding on D.pdfMartinez Company had 210,000 shares of common stock outstanding on D.pdf
Martinez Company had 210,000 shares of common stock outstanding on D.pdf
 
Is fat soluble produced in the skin Vitamin K Cortisol Vitamin A V.pdf
Is fat soluble produced in the skin  Vitamin K Cortisol Vitamin A V.pdfIs fat soluble produced in the skin  Vitamin K Cortisol Vitamin A V.pdf
Is fat soluble produced in the skin Vitamin K Cortisol Vitamin A V.pdf
 
In bacterial chemotaxis, which feature of the bacterial flagella det.pdf
In bacterial chemotaxis, which feature of the bacterial flagella det.pdfIn bacterial chemotaxis, which feature of the bacterial flagella det.pdf
In bacterial chemotaxis, which feature of the bacterial flagella det.pdf
 
How would I describe the rejection region of the test that has si.pdf
How would I describe the rejection region of the test that has si.pdfHow would I describe the rejection region of the test that has si.pdf
How would I describe the rejection region of the test that has si.pdf
 
How exactly do Protease inhibitors help HIV patients fight the disea.pdf
How exactly do Protease inhibitors help HIV patients fight the disea.pdfHow exactly do Protease inhibitors help HIV patients fight the disea.pdf
How exactly do Protease inhibitors help HIV patients fight the disea.pdf
 
Fred, Tom, Jenny and Sarah pooled their money and purchased a packet .pdf
Fred, Tom, Jenny and Sarah pooled their money and purchased a packet .pdfFred, Tom, Jenny and Sarah pooled their money and purchased a packet .pdf
Fred, Tom, Jenny and Sarah pooled their money and purchased a packet .pdf
 
Explain the various categories of ratio analysis and provide example.pdf
Explain the various categories of ratio analysis and provide example.pdfExplain the various categories of ratio analysis and provide example.pdf
Explain the various categories of ratio analysis and provide example.pdf
 
Factor the expression completely. Begin by factoring out the lowest .pdf
Factor the expression completely. Begin by factoring out the lowest .pdfFactor the expression completely. Begin by factoring out the lowest .pdf
Factor the expression completely. Begin by factoring out the lowest .pdf
 
Describe the principal costs incurred in the business that employs y.pdf
Describe the principal costs incurred in the business that employs y.pdfDescribe the principal costs incurred in the business that employs y.pdf
Describe the principal costs incurred in the business that employs y.pdf
 
Compare and contrast swabs and contact (RODAC) plates for their abil.pdf
Compare and contrast swabs and contact (RODAC) plates for their abil.pdfCompare and contrast swabs and contact (RODAC) plates for their abil.pdf
Compare and contrast swabs and contact (RODAC) plates for their abil.pdf
 
Briefly explain the ventral and dorsal body cavities and the membran.pdf
Briefly explain the ventral and dorsal body cavities and the membran.pdfBriefly explain the ventral and dorsal body cavities and the membran.pdf
Briefly explain the ventral and dorsal body cavities and the membran.pdf
 
a connective tissue that is responsible for the shape of our nose..pdf
a connective tissue that is responsible for the shape of our nose..pdfa connective tissue that is responsible for the shape of our nose..pdf
a connective tissue that is responsible for the shape of our nose..pdf
 
6. In humans, having a widow’s peak (W) is dominant to not having a .pdf
6. In humans, having a widow’s peak (W) is dominant to not having a .pdf6. In humans, having a widow’s peak (W) is dominant to not having a .pdf
6. In humans, having a widow’s peak (W) is dominant to not having a .pdf
 
28. What is the proposed role of thioredoxin in seed protein mobiliz.pdf
28. What is the proposed role of thioredoxin in seed protein mobiliz.pdf28. What is the proposed role of thioredoxin in seed protein mobiliz.pdf
28. What is the proposed role of thioredoxin in seed protein mobiliz.pdf
 
Write a short assembly code that does the followingAdd the conten.pdf
Write a short assembly code that does the followingAdd the conten.pdfWrite a short assembly code that does the followingAdd the conten.pdf
Write a short assembly code that does the followingAdd the conten.pdf
 
Write a 250-300 word abstract explaining that the internet is the gr.pdf
Write a 250-300 word abstract explaining that the internet is the gr.pdfWrite a 250-300 word abstract explaining that the internet is the gr.pdf
Write a 250-300 word abstract explaining that the internet is the gr.pdf
 
Write a functionWe want a function, called split, that has three p.pdf
Write a functionWe want a function, called split, that has three p.pdfWrite a functionWe want a function, called split, that has three p.pdf
Write a functionWe want a function, called split, that has three p.pdf
 
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdf
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdfWhy is it recommended that vegans take an oral vitamin B12 supplemen.pdf
Why is it recommended that vegans take an oral vitamin B12 supplemen.pdf
 
16. The respirations that accompany metabolic acidosis are frequentl.pdf
16. The respirations that accompany metabolic acidosis are frequentl.pdf16. The respirations that accompany metabolic acidosis are frequentl.pdf
16. The respirations that accompany metabolic acidosis are frequentl.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 

Recently uploaded (20)

Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 

Write a program in java in which you will build the“Sink theShipsGam.pdf

  • 1. Write a program in java in which you will build the“Sink theShipsGame”. The Game has a8 x 8 grid and threeships. Each ship takes up exactly three cells. In the game, it’s you against thecomputer, but unlike the real battleship game, you don’t place any ships on yourown. Instead, your job is to sink the computer’s ship in the fewest number of guess. Goal:Sink all the computer’s ships(three in this case)in the fewest number ofguesses. You’re given a rating or level, based on how well you perform.Setup:When the game program is launched, the computerplaces three ships on a8x 8 grid(for an example, see the figure below).The ships can be placed eithervertically or horizontally (no other placement is valid)on empty cells of the grid.When that’scomplete the game asks for your first guess. The computer will prompt you to enter a guess(a cell), that you will type at the command-line as “1 3”(where “1 3” means 3rdcell ofthe 1strow), “45”, etc.. In response to your guess, you will see a result at thecommand line,either “Hit”, “Miss”, “Kill” (or whatever the lucky battleship of the dayis!). When you have sank all three battleships, the game ends by printing out your rating. Here is a sample run of the game: Your goal is to sink three ships. Battleship1, Battleship2, Battleship3 Try to sink them all in the fewest number of guesses Enter a guess [row (1 to 8)] [col (1 to 8)]: 1 3 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 2 1 hit Enter a guess [row (1 to 8)] [col (1 to 8)]: 2 2 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 1 hit Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 1 kill Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 3 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 1 7 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 3 hit Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 4 hit
  • 2. Enter a guess [row (1 to 8)] [col (1 to 8)]: 4 5 kill Enter a guess [row (1 to 8)] [col (1 to 8)]: 5 1 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 3 1 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 6 1 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 61 1 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 6 1 miss Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 4 hit Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 5 hit Enter a guess [row (1 to 8)] [col (1 to 8)]: 8 6 kill All Ships are sank! It only took you 18 guesses. You got out before your options sank. When player can finish the game within 20 guesses, print the following message (where xx is the number of guesses): All Ships are sank! It only took you XX guesses. You got out before your options sank. If it takes more than 20 guesses, print the following message All Ships are sank! Took you long enough. XX guesses. Fish are dancing with your options. The java program should terminate after 25 guesses and it should reveal the positions of the ships and their status. Solution Please follow the code and comments for description :
  • 3. CODE : import java.util.Random; // required imports for the code import java.util.Scanner; public class SinktheShipsGame { // class to run the code public static void main(String[] args) { // driver method int[][] board = new int[8][8]; // required initialisations int[][] ships = new int[3][2]; int[] shoot = new int[2]; int guesses = 0, shotHit = 0; boardPlacement(board); // calling the method to print the initial board shipsPlacement(ships); // method to print the ships and their repsective placements System.out.println(); do { showTheBoard(board); // print the board to console shoot(shoot); // checking the shot from the user guesses++; // incrementing the guesses if (hit(shoot, ships)) { // checking the shot given by the user System.out.printf("You hit a ship.! "); // print the result shotHit++; // incrementing the shot hits } else { System.out.printf("You Missed a ship.! "); //hint(shoot, ships, guesses); } changeTheBoard(shoot, ships, board); // updating the board with the present rsult if(guesses >= 25) { // checking for the guess count break; // breaking the loop if is greater than 25 } } while (shotHit != 3); // iterating the loop till all the 3 ships are shot if(guesses < 20){ // print the result based on the guess count System.out.println(" All Ships are sank! It only took you " + guesses + " guesses. You got out before your options sank.");
  • 4. } else if (guesses >= 20) { System.out.println(" All Ships are sank! Took You Long Enough. " + guesses + " guesses. Fish are dancing with your options."); } else if (guesses > 25) { System.out.println("You Lost.! The Result is : "); showTheBoard(board); } } public static void boardPlacement(int[][] board) { // method to place the board and the results cells for (int row = 0; row < 8; row++) { for (int column = 0; column < 8; column++) { board[row][column] = -1; // returns the desired values } } } public static void showTheBoard(int[][] board) { // method to shoe the initial or the resultant board System.out.println(" t1 t2 t3 t4 t5 t6 t7 t8"); System.out.println(); for (int row = 0; row < 8; row++) { // iterating over the rows and columns System.out.print((row + 1) + ""); for (int column = 0; column < 8; column++) { if (board[row][column] == -1) { System.out.print("t" + "~"); // print the respective results } else if (board[row][column] == 0) { System.out.print("t" + "*"); } else if (board[row][column] == 1) { System.out.print("t" + "X"); } } System.out.println(); } } public static void shipsPlacement(int[][] ships) { // initial placement of the ships Random random = new Random();
  • 5. for (int ship = 0; ship < 3; ship++) { // iterating over the ships count ships[ship][0] = random.nextInt(8); // getting the random numnber for the cell value ships[ship][1] = random.nextInt(8); for (int last = 0; last < ship; last++) { // checking for the last placement of the cell if ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1])) { do { ships[ship][0] = random.nextInt(8); ships[ship][1] = random.nextInt(8); } while ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1])); } } } } public static void shoot(int[] shoot) { // method that checks and updates the shoot value Scanner input = new Scanner(System.in); System.out.printf("Enter a guess [row (1 to 8)] [col (1 to 8)] : "); shoot[0] = input.nextInt(); // getting the values form the user shoot[0]--; shoot[1] = input.nextInt(); shoot[1]--; } public static boolean hit(int[] shoot, int[][] ships) { // checking the method to see if the hit is a success or not for (int ship = 0; ship < ships.length; ship++) { if (shoot[0] == ships[ship][0] && shoot[1] == ships[ship][1]) { return true; } } return false; } public static void changeTheBoard(int[] shoot, int[][] ships, int[][] board) { // method that changes the board if (hit(shoot, ships)) {
  • 6. board[shoot[0]][shoot[1]] = 1; // updating the values } else { board[shoot[0]][shoot[1]] = 0; } } } OUTPUT : 1 2 3 4 5 6 7 8 1 ~ ~ ~ ~ ~ ~ ~ ~ 2 ~ ~ ~ ~ ~ ~ ~ ~ 3 ~ ~ ~ ~ ~ ~ ~ ~ 4 ~ ~ ~ ~ ~ ~ ~ ~ 5 ~ ~ ~ ~ ~ ~ ~ ~ 6 ~ ~ ~ ~ ~ ~ ~ ~ 7 ~ ~ ~ ~ ~ ~ ~ ~ 8 ~ ~ ~ ~ ~ ~ ~ ~ Enter a guess [row (1 to 8)] [col (1 to 8)] : 1 1 You Missed a ship.! 1 2 3 4 5 6 7 8 1 * ~ ~ ~ ~ ~ ~ ~ 2 ~ ~ ~ ~ ~ ~ ~ ~ 3 ~ ~ ~ ~ ~ ~ ~ ~ 4 ~ ~ ~ ~ ~ ~ ~ ~ 5 ~ ~ ~ ~ ~ ~ ~ ~ 6 ~ ~ ~ ~ ~ ~ ~ ~ 7 ~ ~ ~ ~ ~ ~ ~ ~ 8 ~ ~ ~ ~ ~ ~ ~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