SlideShare a Scribd company logo
send EDITED code please
Battleship.java
package part3;
public class Battleship {
public static void main(String[] args) {
// Generate a grid of 15 columns by 10 rows.
BattleshipGrid aGrid = new BattleshipGrid(10,10);
// Print the grid.
aGrid.print();
}
}
Battleship Grid.java
package part3;
import java.util.Random;
import java.util.Scanner;
public class BattleshipGrid {
private char[][] grid;
private int gridRows, gridColumns;
static final int CARRIER_SIZE = 5;
static final int BATTLESHIP_SIZE = 4;
static final int SUB_SIZE = 3;
static final int DESTROYER_SIZE = 3;
static final int PATROL_SIZE = 2;
static final char CARRIER_CHAR = 'C';
static final char BATTLESHIP_CHAR = 'B';
static final char SUB_CHAR = 'S';
static final char DESTROYER_CHAR = 'D';
static final char PATROL_CHAR = 'P';
static final char WATER_CHAR = '.';
public BattleshipGrid(int columns, int rows){
gridColumns = columns;
gridRows = rows;
// Make a two dimensional array of characters as the grid
grid = new char[gridColumns][gridRows];
// Clear the grid
clear();
// Assign the following ships
assignShip(CARRIER_CHAR, CARRIER_SIZE);
assignShip(BATTLESHIP_CHAR, BATTLESHIP_SIZE);
assignShip(SUB_CHAR, SUB_SIZE);
assignShip(DESTROYER_CHAR, DESTROYER_SIZE);
assignShip(PATROL_CHAR, PATROL_SIZE);
}
// Clear the grid
public void clear(){
for (int row=0; row < gridRows; row++){
for (int column=0; column < gridColumns; column++) grid[column][row] =
WATER_CHAR;
}
}
// Print the grid
public void print(){
for (int row=0; row < gridRows; row++){
for (int column=0; column < gridColumns; column++)
System.out.print(grid[column][row]);
System.out.println("");
}
}
// Assign a ship horizontally on the grid
private boolean assignShipHorizontally(char shipType, int size){
/*
1.2 If horizontal, select a random row to place the ship.
o Select a random column position to start “growing� your ship. The column position
must be less than 10-size of the ship to ensure the ship will fit.
o Look at the next adjacent squares on the grid row to see if they are blank.
o If any of the squares are not blank then the ship will not fit so go back to 1.1.
o If the ship does fit then mark it with its designation.
*/
// Select a row and a starting column to place a ship horizontally
Random randomGenerator = new Random();
int chosenRow = randomGenerator.nextInt(gridRows);
int startingColumn = randomGenerator.nextInt(gridColumns-size);
// Count consecutive grid locations horizontally and see if we can accommodate ship
int countSegments = 0;
for (int c = startingColumn; c < startingColumn+size; c++){
if (grid[c][chosenRow] == WATER_CHAR) countSegments++;
}
// If ship will fit then allocate the ship horizontally
if (countSegments == size){
for (int c = startingColumn; c < startingColumn+size; c++){
grid[c][chosenRow] = shipType;
}
return true;
}
return false;
}
// Assign the ship vertically on the grid
private boolean assignShipVertically(char shipType, int size){
/*
1.3 If vertical, select a random column to place the ship.
o Select a random row position to start “growing� your ship. The row position must
be less than 10-size of the ship to ensure the ship will fit.
o Look at the next adjacent squares on the grid column to see if they are blank.
o If any of the squares are not blank then the ship will not fit so go back to 1.1.
o If the ship does fit then mark it with its designation.
*/
// Select a column and a starting row to place a ship vertically
Random randomGenerator = new Random();
int chosenColumn = randomGenerator.nextInt(gridColumns);
int startingRow = randomGenerator.nextInt(gridRows-size);
// Count consecutive grid locations vertically and see if we can accommodate ship
int countSegments = 0;
for (int r = startingRow; r < startingRow+size; r++){
if (grid[chosenColumn][r] == WATER_CHAR) countSegments++;
}
// If ship will fit then allocate the ship vertically
if (countSegments == size){
for (int r = startingRow; r < startingRow+size; r++){
grid[chosenColumn][r] = shipType;
}
return true;
}
return false;
}
// Assign a ship to the grid
private void assignShip(char shipType, int size){
Random randomGenerator = new Random();
boolean status = false;
do{
// Randomly choose between horizontal and vertical allocation.
// Sometimes an allocation isnʻt possible so roll the dice and try again.
if (randomGenerator.nextInt(2) == 0)
status = assignShipHorizontally(shipType, size);
else
status = assignShipVertically(shipType, size);
} while(status != true);
}
public boolean playGame(){
// Print the board
// 1) write a for loop to iterate through the rows
for (){
// 2) write a for loop to iterate through the columns
for (){
// 3) if grid[column][row] is 'X'
if(){
// 4) print " "+grid[column][row] (use System.out.print)
} else{
// 5) else print " "+WATER_CHAR (use System.out.print)
}
}
System.out.println("");
}
// Ask user for coordinate
// 6) Create a Scanner called sc instantiate it using new Scanner(System.in)
// Ask user to enter a coordinate
System.out.print("Enter a coordinate (col,row): ");
// 7) read in the first integer to an integer called userCol
// 8) read in the second integer to an integer called userRow
// Check if column and row are with in the range of the board
// 9) Check if (userRow is less than 0) or (userRow is greater than or equal to gridRows),
if(){
// 10) use print() method to reveal location of ships
// 11) return false to end game
}
// 12) Check if (userCol is less than 0) or (userCol is greater than or equal to gridColumns),
if(){
// 13) use print() method to reveal location of ships
// 14) return false to end game
}
// 15) Check if grid[userCol][userRow] intersects with a ship,
if(){
// 16) set value at userCol, userRow to 'X'
}
// return true to continue playing the game
return true;
}
} Part 3: Modify Battleship Map Creator For this part, you will write a playGame() method that
will print the board, ask a user for a coordinate, check if a ship is at this coordinate and mark an
X for hit. If a coordinate entered is outside the range of the board, show the ships and end the
game. In BattelshipGrid.java: » Locate the playGame() method in the BattelshipGrid.java file ·
write the code for steps 1-16 In Battelship.java: At line 11, comment out aGrid.print(); At line
12, add the following while loop. o while(aGrid.playGame()); » » Please note You can only have
spaces between coordinates when you input them. Otherwise an exception will be thrown » » If
you sink all the ships, the game will not end o For extra practice, add code that will end the game
when all ships are sunk
Solution
package part3;
public class Battleship {
public static void main(String[] args) {
// Generate a grid of 15 columns by 10 rows.
BattleshipGrid aGrid = new BattleshipGrid(10,10);
// Print the grid.
// aGrid.print();
while(aGird.playGame());
}
}
package part3;
import java.util.Random;
import java.util.Scanner;
public class BattleshipGrid {
private char[][] grid;
private int gridRows, gridColumns;
static final int CARRIER_SIZE = 5;
static final int BATTLESHIP_SIZE = 4;
static final int SUB_SIZE = 3;
static final int DESTROYER_SIZE = 3;
static final int PATROL_SIZE = 2;
static final char CARRIER_CHAR = 'C';
static final char BATTLESHIP_CHAR = 'B';
static final char SUB_CHAR = 'S';
static final char DESTROYER_CHAR = 'D';
static final char PATROL_CHAR = 'P';
static final char WATER_CHAR = '.';
public BattleshipGrid(int columns, int rows){
gridColumns = columns;
gridRows = rows;
// Make a two dimensional array of characters as the grid
grid = new char[gridColumns][gridRows];
// Clear the grid
clear();
// Assign the following ships
assignShip(CARRIER_CHAR, CARRIER_SIZE);
assignShip(BATTLESHIP_CHAR, BATTLESHIP_SIZE);
assignShip(SUB_CHAR, SUB_SIZE);
assignShip(DESTROYER_CHAR, DESTROYER_SIZE);
assignShip(PATROL_CHAR, PATROL_SIZE);
}
// Clear the grid
public void clear(){
for (int row=0; row < gridRows; row++){
for (int column=0; column < gridColumns; column++) grid[column][row] =
WATER_CHAR;
}
}
// Print the grid
public void print(){
for (int row=0; row < gridRows; row++){
for (int column=0; column < gridColumns; column++)
System.out.print(grid[column][row]);
System.out.println("");
}
}
// Assign a ship horizontally on the grid
private boolean assignShipHorizontally(char shipType, int size){
/*
1.2 If horizontal, select a random row to place the ship.
o Select a random column position to start “growing� your ship. The column position
must be less than 10-size of the ship to ensure the ship will fit.
o Look at the next adjacent squares on the grid row to see if they are blank.
o If any of the squares are not blank then the ship will not fit so go back to 1.1.
o If the ship does fit then mark it with its designation.
*/
// Select a row and a starting column to place a ship horizontally
Random randomGenerator = new Random();
int chosenRow = randomGenerator.nextInt(gridRows);
int startingColumn = randomGenerator.nextInt(gridColumns-size);
// Count consecutive grid locations horizontally and see if we can accommodate ship
int countSegments = 0;
for (int c = startingColumn; c < startingColumn+size; c++){
if (grid[c][chosenRow] == WATER_CHAR) countSegments++;
}
// If ship will fit then allocate the ship horizontally
if (countSegments == size){
for (int c = startingColumn; c < startingColumn+size; c++){
grid[c][chosenRow] = shipType;
}
return true;
}
return false;
}
// Assign the ship vertically on the grid
private boolean assignShipVertically(char shipType, int size){
/*
1.3 If vertical, select a random column to place the ship.
o Select a random row position to start “growing� your ship. The row position must
be less than 10-size of the ship to ensure the ship will fit.
o Look at the next adjacent squares on the grid column to see if they are blank.
o If any of the squares are not blank then the ship will not fit so go back to 1.1.
o If the ship does fit then mark it with its designation.
*/
// Select a column and a starting row to place a ship vertically
Random randomGenerator = new Random();
int chosenColumn = randomGenerator.nextInt(gridColumns);
int startingRow = randomGenerator.nextInt(gridRows-size);
// Count consecutive grid locations vertically and see if we can accommodate ship
int countSegments = 0;
for (int r = startingRow; r < startingRow+size; r++){
if (grid[chosenColumn][r] == WATER_CHAR) countSegments++;
}
// If ship will fit then allocate the ship vertically
if (countSegments == size){
for (int r = startingRow; r < startingRow+size; r++){
grid[chosenColumn][r] = shipType;
}
return true;
}
return false;
}
// Assign a ship to the grid
private void assignShip(char shipType, int size){
Random randomGenerator = new Random();
boolean status = false;
do{
// Randomly choose between horizontal and vertical allocation.
// Sometimes an allocation isnʻt possible so roll the dice and try again.
if (randomGenerator.nextInt(2) == 0)
status = assignShipHorizontally(shipType, size);
else
status = assignShipVertically(shipType, size);
} while(status != true);
}
public boolean playGame(){
// Print the board
// 1) write a for loop to iterate through the rows
for (int row=0;row=gridRows){
// 10) use print() method to reveal location of ships
print();
// 11) return false to end game
return false;
}
// 12) Check if (userCol is less than 0) or (userCol is greater than or equal to gridColumns),
if(userCol<0 || userCol>=gridColumns){
// 13) use print() method to reveal location of ships
print();
// 14) return false to end game
return false;
}
// 15) Check if grid[userCol][userRow] intersects with a ship,
if(grd[userCol][userRow]='C' || grid[userCol][userRow]='B' ||
grid[userCol][userRow]='S' || grid[userCol][userRow]='D' || grid[userCol][userRow]='P'){
// 16) set value at userCol, userRow to 'X'
grid[userCol][userRow]='X';
}
// return true to continue playing the game
return true;
}
}

More Related Content

More from irshadoptical

In practice, a RAM is used to simulate the operation of a stack by m.pdf
In practice, a RAM is used to simulate the operation of a stack by m.pdfIn practice, a RAM is used to simulate the operation of a stack by m.pdf
In practice, a RAM is used to simulate the operation of a stack by m.pdf
irshadoptical
 
i need help to edit the two methods below so that i can have them wo.pdf
i need help to edit the two methods below so that i can have them wo.pdfi need help to edit the two methods below so that i can have them wo.pdf
i need help to edit the two methods below so that i can have them wo.pdf
irshadoptical
 
Help!! Which of the following correctly lists the simple molecules t.pdf
Help!! Which of the following correctly lists the simple molecules t.pdfHelp!! Which of the following correctly lists the simple molecules t.pdf
Help!! Which of the following correctly lists the simple molecules t.pdf
irshadoptical
 
How does feasibility differ in an agile environment in comparison to.pdf
How does feasibility differ in an agile environment in comparison to.pdfHow does feasibility differ in an agile environment in comparison to.pdf
How does feasibility differ in an agile environment in comparison to.pdf
irshadoptical
 
describe a real-life example of selection against a homozygous reces.pdf
describe a real-life example of selection against a homozygous reces.pdfdescribe a real-life example of selection against a homozygous reces.pdf
describe a real-life example of selection against a homozygous reces.pdf
irshadoptical
 
Define a motor unit. What roles do motor units play in graded contrac.pdf
Define a motor unit. What roles do motor units play in graded contrac.pdfDefine a motor unit. What roles do motor units play in graded contrac.pdf
Define a motor unit. What roles do motor units play in graded contrac.pdf
irshadoptical
 
An antibody is a protein that has which level of protein structure .pdf
An antibody is a protein that has which level of protein structure  .pdfAn antibody is a protein that has which level of protein structure  .pdf
An antibody is a protein that has which level of protein structure .pdf
irshadoptical
 
C++ PROGRAMThis program builds on the code below#include iostr.pdf
C++ PROGRAMThis program builds on the code below#include iostr.pdfC++ PROGRAMThis program builds on the code below#include iostr.pdf
C++ PROGRAMThis program builds on the code below#include iostr.pdf
irshadoptical
 
You are in charge of the investigation regarding possible exposur.pdf
You are in charge of the investigation regarding possible exposur.pdfYou are in charge of the investigation regarding possible exposur.pdf
You are in charge of the investigation regarding possible exposur.pdf
irshadoptical
 
Which of the following is not a product of the light reactions of ph.pdf
Which of the following is not a product of the light reactions of ph.pdfWhich of the following is not a product of the light reactions of ph.pdf
Which of the following is not a product of the light reactions of ph.pdf
irshadoptical
 
Write a line of code to create a Print Writer to write to the file .pdf
Write a line of code to create a Print Writer to write to the file .pdfWrite a line of code to create a Print Writer to write to the file .pdf
Write a line of code to create a Print Writer to write to the file .pdf
irshadoptical
 
what is the difference bettween cotranslational import and posttrans.pdf
what is the difference bettween cotranslational import and posttrans.pdfwhat is the difference bettween cotranslational import and posttrans.pdf
what is the difference bettween cotranslational import and posttrans.pdf
irshadoptical
 
What is the meaning of critical periods in neonatal development Wha.pdf
What is the meaning of critical periods in neonatal development Wha.pdfWhat is the meaning of critical periods in neonatal development Wha.pdf
What is the meaning of critical periods in neonatal development Wha.pdf
irshadoptical
 
What are the major differences between foreign bonds and Eurobonds .pdf
What are the major differences between foreign bonds and Eurobonds .pdfWhat are the major differences between foreign bonds and Eurobonds .pdf
What are the major differences between foreign bonds and Eurobonds .pdf
irshadoptical
 
What is meant by ecological fallacySolutionAnswerThe term .pdf
What is meant by ecological fallacySolutionAnswerThe term .pdfWhat is meant by ecological fallacySolutionAnswerThe term .pdf
What is meant by ecological fallacySolutionAnswerThe term .pdf
irshadoptical
 
What are the two main branches of Non-Euclidean Geometry What is the.pdf
What are the two main branches of Non-Euclidean Geometry What is the.pdfWhat are the two main branches of Non-Euclidean Geometry What is the.pdf
What are the two main branches of Non-Euclidean Geometry What is the.pdf
irshadoptical
 
By what transport method does oxygen enter the blood from the alveol.pdf
By what transport method does oxygen enter the blood from the alveol.pdfBy what transport method does oxygen enter the blood from the alveol.pdf
By what transport method does oxygen enter the blood from the alveol.pdf
irshadoptical
 
All of these are examples of evidence used to support the hypothesis.pdf
All of these are examples of evidence used to support the hypothesis.pdfAll of these are examples of evidence used to support the hypothesis.pdf
All of these are examples of evidence used to support the hypothesis.pdf
irshadoptical
 
A 28 year-old biologist makes a trip to study life forms in a distan.pdf
A 28 year-old biologist makes a trip to study life forms in a distan.pdfA 28 year-old biologist makes a trip to study life forms in a distan.pdf
A 28 year-old biologist makes a trip to study life forms in a distan.pdf
irshadoptical
 
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
irshadoptical
 

More from irshadoptical (20)

In practice, a RAM is used to simulate the operation of a stack by m.pdf
In practice, a RAM is used to simulate the operation of a stack by m.pdfIn practice, a RAM is used to simulate the operation of a stack by m.pdf
In practice, a RAM is used to simulate the operation of a stack by m.pdf
 
i need help to edit the two methods below so that i can have them wo.pdf
i need help to edit the two methods below so that i can have them wo.pdfi need help to edit the two methods below so that i can have them wo.pdf
i need help to edit the two methods below so that i can have them wo.pdf
 
Help!! Which of the following correctly lists the simple molecules t.pdf
Help!! Which of the following correctly lists the simple molecules t.pdfHelp!! Which of the following correctly lists the simple molecules t.pdf
Help!! Which of the following correctly lists the simple molecules t.pdf
 
How does feasibility differ in an agile environment in comparison to.pdf
How does feasibility differ in an agile environment in comparison to.pdfHow does feasibility differ in an agile environment in comparison to.pdf
How does feasibility differ in an agile environment in comparison to.pdf
 
describe a real-life example of selection against a homozygous reces.pdf
describe a real-life example of selection against a homozygous reces.pdfdescribe a real-life example of selection against a homozygous reces.pdf
describe a real-life example of selection against a homozygous reces.pdf
 
Define a motor unit. What roles do motor units play in graded contrac.pdf
Define a motor unit. What roles do motor units play in graded contrac.pdfDefine a motor unit. What roles do motor units play in graded contrac.pdf
Define a motor unit. What roles do motor units play in graded contrac.pdf
 
An antibody is a protein that has which level of protein structure .pdf
An antibody is a protein that has which level of protein structure  .pdfAn antibody is a protein that has which level of protein structure  .pdf
An antibody is a protein that has which level of protein structure .pdf
 
C++ PROGRAMThis program builds on the code below#include iostr.pdf
C++ PROGRAMThis program builds on the code below#include iostr.pdfC++ PROGRAMThis program builds on the code below#include iostr.pdf
C++ PROGRAMThis program builds on the code below#include iostr.pdf
 
You are in charge of the investigation regarding possible exposur.pdf
You are in charge of the investigation regarding possible exposur.pdfYou are in charge of the investigation regarding possible exposur.pdf
You are in charge of the investigation regarding possible exposur.pdf
 
Which of the following is not a product of the light reactions of ph.pdf
Which of the following is not a product of the light reactions of ph.pdfWhich of the following is not a product of the light reactions of ph.pdf
Which of the following is not a product of the light reactions of ph.pdf
 
Write a line of code to create a Print Writer to write to the file .pdf
Write a line of code to create a Print Writer to write to the file .pdfWrite a line of code to create a Print Writer to write to the file .pdf
Write a line of code to create a Print Writer to write to the file .pdf
 
what is the difference bettween cotranslational import and posttrans.pdf
what is the difference bettween cotranslational import and posttrans.pdfwhat is the difference bettween cotranslational import and posttrans.pdf
what is the difference bettween cotranslational import and posttrans.pdf
 
What is the meaning of critical periods in neonatal development Wha.pdf
What is the meaning of critical periods in neonatal development Wha.pdfWhat is the meaning of critical periods in neonatal development Wha.pdf
What is the meaning of critical periods in neonatal development Wha.pdf
 
What are the major differences between foreign bonds and Eurobonds .pdf
What are the major differences between foreign bonds and Eurobonds .pdfWhat are the major differences between foreign bonds and Eurobonds .pdf
What are the major differences between foreign bonds and Eurobonds .pdf
 
What is meant by ecological fallacySolutionAnswerThe term .pdf
What is meant by ecological fallacySolutionAnswerThe term .pdfWhat is meant by ecological fallacySolutionAnswerThe term .pdf
What is meant by ecological fallacySolutionAnswerThe term .pdf
 
What are the two main branches of Non-Euclidean Geometry What is the.pdf
What are the two main branches of Non-Euclidean Geometry What is the.pdfWhat are the two main branches of Non-Euclidean Geometry What is the.pdf
What are the two main branches of Non-Euclidean Geometry What is the.pdf
 
By what transport method does oxygen enter the blood from the alveol.pdf
By what transport method does oxygen enter the blood from the alveol.pdfBy what transport method does oxygen enter the blood from the alveol.pdf
By what transport method does oxygen enter the blood from the alveol.pdf
 
All of these are examples of evidence used to support the hypothesis.pdf
All of these are examples of evidence used to support the hypothesis.pdfAll of these are examples of evidence used to support the hypothesis.pdf
All of these are examples of evidence used to support the hypothesis.pdf
 
A 28 year-old biologist makes a trip to study life forms in a distan.pdf
A 28 year-old biologist makes a trip to study life forms in a distan.pdfA 28 year-old biologist makes a trip to study life forms in a distan.pdf
A 28 year-old biologist makes a trip to study life forms in a distan.pdf
 
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
4. Name the following compounds CO2 CH CH3 CH20H CH3COOH 5. Water ha.pdf
 

Recently uploaded

ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 

Recently uploaded (20)

ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 

send EDITED code pleaseBattleship.javapackage part3;public cla.pdf

  • 1. send EDITED code please Battleship.java package part3; public class Battleship { public static void main(String[] args) { // Generate a grid of 15 columns by 10 rows. BattleshipGrid aGrid = new BattleshipGrid(10,10); // Print the grid. aGrid.print(); } } Battleship Grid.java package part3; import java.util.Random; import java.util.Scanner; public class BattleshipGrid { private char[][] grid; private int gridRows, gridColumns; static final int CARRIER_SIZE = 5; static final int BATTLESHIP_SIZE = 4; static final int SUB_SIZE = 3; static final int DESTROYER_SIZE = 3; static final int PATROL_SIZE = 2; static final char CARRIER_CHAR = 'C'; static final char BATTLESHIP_CHAR = 'B'; static final char SUB_CHAR = 'S'; static final char DESTROYER_CHAR = 'D'; static final char PATROL_CHAR = 'P'; static final char WATER_CHAR = '.'; public BattleshipGrid(int columns, int rows){
  • 2. gridColumns = columns; gridRows = rows; // Make a two dimensional array of characters as the grid grid = new char[gridColumns][gridRows]; // Clear the grid clear(); // Assign the following ships assignShip(CARRIER_CHAR, CARRIER_SIZE); assignShip(BATTLESHIP_CHAR, BATTLESHIP_SIZE); assignShip(SUB_CHAR, SUB_SIZE); assignShip(DESTROYER_CHAR, DESTROYER_SIZE); assignShip(PATROL_CHAR, PATROL_SIZE); } // Clear the grid public void clear(){ for (int row=0; row < gridRows; row++){ for (int column=0; column < gridColumns; column++) grid[column][row] = WATER_CHAR; } } // Print the grid public void print(){ for (int row=0; row < gridRows; row++){ for (int column=0; column < gridColumns; column++) System.out.print(grid[column][row]); System.out.println(""); } } // Assign a ship horizontally on the grid private boolean assignShipHorizontally(char shipType, int size){
  • 3. /* 1.2 If horizontal, select a random row to place the ship. o Select a random column position to start “growingâ€? your ship. The column position must be less than 10-size of the ship to ensure the ship will fit. o Look at the next adjacent squares on the grid row to see if they are blank. o If any of the squares are not blank then the ship will not fit so go back to 1.1. o If the ship does fit then mark it with its designation. */ // Select a row and a starting column to place a ship horizontally Random randomGenerator = new Random(); int chosenRow = randomGenerator.nextInt(gridRows); int startingColumn = randomGenerator.nextInt(gridColumns-size); // Count consecutive grid locations horizontally and see if we can accommodate ship int countSegments = 0; for (int c = startingColumn; c < startingColumn+size; c++){ if (grid[c][chosenRow] == WATER_CHAR) countSegments++; } // If ship will fit then allocate the ship horizontally if (countSegments == size){ for (int c = startingColumn; c < startingColumn+size; c++){ grid[c][chosenRow] = shipType; } return true; } return false; } // Assign the ship vertically on the grid private boolean assignShipVertically(char shipType, int size){ /* 1.3 If vertical, select a random column to place the ship. o Select a random row position to start “growingâ€? your ship. The row position must
  • 4. be less than 10-size of the ship to ensure the ship will fit. o Look at the next adjacent squares on the grid column to see if they are blank. o If any of the squares are not blank then the ship will not fit so go back to 1.1. o If the ship does fit then mark it with its designation. */ // Select a column and a starting row to place a ship vertically Random randomGenerator = new Random(); int chosenColumn = randomGenerator.nextInt(gridColumns); int startingRow = randomGenerator.nextInt(gridRows-size); // Count consecutive grid locations vertically and see if we can accommodate ship int countSegments = 0; for (int r = startingRow; r < startingRow+size; r++){ if (grid[chosenColumn][r] == WATER_CHAR) countSegments++; } // If ship will fit then allocate the ship vertically if (countSegments == size){ for (int r = startingRow; r < startingRow+size; r++){ grid[chosenColumn][r] = shipType; } return true; } return false; } // Assign a ship to the grid private void assignShip(char shipType, int size){ Random randomGenerator = new Random(); boolean status = false; do{ // Randomly choose between horizontal and vertical allocation. // Sometimes an allocation isnÊ»t possible so roll the dice and try again.
  • 5. if (randomGenerator.nextInt(2) == 0) status = assignShipHorizontally(shipType, size); else status = assignShipVertically(shipType, size); } while(status != true); } public boolean playGame(){ // Print the board // 1) write a for loop to iterate through the rows for (){ // 2) write a for loop to iterate through the columns for (){ // 3) if grid[column][row] is 'X' if(){ // 4) print " "+grid[column][row] (use System.out.print) } else{ // 5) else print " "+WATER_CHAR (use System.out.print) } } System.out.println(""); } // Ask user for coordinate // 6) Create a Scanner called sc instantiate it using new Scanner(System.in) // Ask user to enter a coordinate System.out.print("Enter a coordinate (col,row): "); // 7) read in the first integer to an integer called userCol // 8) read in the second integer to an integer called userRow // Check if column and row are with in the range of the board // 9) Check if (userRow is less than 0) or (userRow is greater than or equal to gridRows), if(){ // 10) use print() method to reveal location of ships // 11) return false to end game
  • 6. } // 12) Check if (userCol is less than 0) or (userCol is greater than or equal to gridColumns), if(){ // 13) use print() method to reveal location of ships // 14) return false to end game } // 15) Check if grid[userCol][userRow] intersects with a ship, if(){ // 16) set value at userCol, userRow to 'X' } // return true to continue playing the game return true; } } Part 3: Modify Battleship Map Creator For this part, you will write a playGame() method that will print the board, ask a user for a coordinate, check if a ship is at this coordinate and mark an X for hit. If a coordinate entered is outside the range of the board, show the ships and end the game. In BattelshipGrid.java: » Locate the playGame() method in the BattelshipGrid.java file · write the code for steps 1-16 In Battelship.java: At line 11, comment out aGrid.print(); At line 12, add the following while loop. o while(aGrid.playGame()); » » Please note You can only have spaces between coordinates when you input them. Otherwise an exception will be thrown » » If you sink all the ships, the game will not end o For extra practice, add code that will end the game when all ships are sunk Solution package part3; public class Battleship { public static void main(String[] args) { // Generate a grid of 15 columns by 10 rows. BattleshipGrid aGrid = new BattleshipGrid(10,10); // Print the grid. // aGrid.print();
  • 7. while(aGird.playGame()); } } package part3; import java.util.Random; import java.util.Scanner; public class BattleshipGrid { private char[][] grid; private int gridRows, gridColumns; static final int CARRIER_SIZE = 5; static final int BATTLESHIP_SIZE = 4; static final int SUB_SIZE = 3; static final int DESTROYER_SIZE = 3; static final int PATROL_SIZE = 2; static final char CARRIER_CHAR = 'C'; static final char BATTLESHIP_CHAR = 'B'; static final char SUB_CHAR = 'S'; static final char DESTROYER_CHAR = 'D'; static final char PATROL_CHAR = 'P'; static final char WATER_CHAR = '.'; public BattleshipGrid(int columns, int rows){ gridColumns = columns; gridRows = rows; // Make a two dimensional array of characters as the grid grid = new char[gridColumns][gridRows]; // Clear the grid clear(); // Assign the following ships assignShip(CARRIER_CHAR, CARRIER_SIZE); assignShip(BATTLESHIP_CHAR, BATTLESHIP_SIZE);
  • 8. assignShip(SUB_CHAR, SUB_SIZE); assignShip(DESTROYER_CHAR, DESTROYER_SIZE); assignShip(PATROL_CHAR, PATROL_SIZE); } // Clear the grid public void clear(){ for (int row=0; row < gridRows; row++){ for (int column=0; column < gridColumns; column++) grid[column][row] = WATER_CHAR; } } // Print the grid public void print(){ for (int row=0; row < gridRows; row++){ for (int column=0; column < gridColumns; column++) System.out.print(grid[column][row]); System.out.println(""); } } // Assign a ship horizontally on the grid private boolean assignShipHorizontally(char shipType, int size){ /* 1.2 If horizontal, select a random row to place the ship. o Select a random column position to start “growingâ€? your ship. The column position must be less than 10-size of the ship to ensure the ship will fit. o Look at the next adjacent squares on the grid row to see if they are blank. o If any of the squares are not blank then the ship will not fit so go back to 1.1. o If the ship does fit then mark it with its designation. */ // Select a row and a starting column to place a ship horizontally Random randomGenerator = new Random();
  • 9. int chosenRow = randomGenerator.nextInt(gridRows); int startingColumn = randomGenerator.nextInt(gridColumns-size); // Count consecutive grid locations horizontally and see if we can accommodate ship int countSegments = 0; for (int c = startingColumn; c < startingColumn+size; c++){ if (grid[c][chosenRow] == WATER_CHAR) countSegments++; } // If ship will fit then allocate the ship horizontally if (countSegments == size){ for (int c = startingColumn; c < startingColumn+size; c++){ grid[c][chosenRow] = shipType; } return true; } return false; } // Assign the ship vertically on the grid private boolean assignShipVertically(char shipType, int size){ /* 1.3 If vertical, select a random column to place the ship. o Select a random row position to start “growingâ€? your ship. The row position must be less than 10-size of the ship to ensure the ship will fit. o Look at the next adjacent squares on the grid column to see if they are blank. o If any of the squares are not blank then the ship will not fit so go back to 1.1. o If the ship does fit then mark it with its designation. */ // Select a column and a starting row to place a ship vertically Random randomGenerator = new Random(); int chosenColumn = randomGenerator.nextInt(gridColumns); int startingRow = randomGenerator.nextInt(gridRows-size); // Count consecutive grid locations vertically and see if we can accommodate ship
  • 10. int countSegments = 0; for (int r = startingRow; r < startingRow+size; r++){ if (grid[chosenColumn][r] == WATER_CHAR) countSegments++; } // If ship will fit then allocate the ship vertically if (countSegments == size){ for (int r = startingRow; r < startingRow+size; r++){ grid[chosenColumn][r] = shipType; } return true; } return false; } // Assign a ship to the grid private void assignShip(char shipType, int size){ Random randomGenerator = new Random(); boolean status = false; do{ // Randomly choose between horizontal and vertical allocation. // Sometimes an allocation isnÊ»t possible so roll the dice and try again. if (randomGenerator.nextInt(2) == 0) status = assignShipHorizontally(shipType, size); else status = assignShipVertically(shipType, size); } while(status != true); } public boolean playGame(){ // Print the board // 1) write a for loop to iterate through the rows for (int row=0;row=gridRows){
  • 11. // 10) use print() method to reveal location of ships print(); // 11) return false to end game return false; } // 12) Check if (userCol is less than 0) or (userCol is greater than or equal to gridColumns), if(userCol<0 || userCol>=gridColumns){ // 13) use print() method to reveal location of ships print(); // 14) return false to end game return false; } // 15) Check if grid[userCol][userRow] intersects with a ship, if(grd[userCol][userRow]='C' || grid[userCol][userRow]='B' || grid[userCol][userRow]='S' || grid[userCol][userRow]='D' || grid[userCol][userRow]='P'){ // 16) set value at userCol, userRow to 'X' grid[userCol][userRow]='X'; } // return true to continue playing the game return true; } }