SlideShare a Scribd company logo
1 of 17
Download to read offline
The following code, is a one player battleship game in JAVA. Im trying to Enhance the game to
be a two player game (were a player plays aggainst a computer opponent). With TWO boards
displayed side by side. The player and the computer must take turns selecting the coordinates on
their own boards. (the ships cannot be placed adjacent to each other).
BattleShipGame.java
package battleship;
import java.util.ArrayList;
import java.util.Scanner;
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = "Welcome to the World of Battleship!";
break;
case 2: info = "Enter coordinates to fire: ";
break;
case 3: info = "Shots fired: "+ocean.getShotsFired()+", Ships sunk:
"+ocean.getShipsSunk();
break;
case 4: info = "Congratulations! You win!";
break;
case 99: info = "Invalid input. Please re-enter:";
break;
case 100: info = "--------------------------------------------";
break;
case 101: info = " ============================================";
break;
default: info = "Error selection";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(""+i);
}
String[] coordinates = input.split(" ");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(" ");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coordinates = getCoordinates(input);
int row = coordinates[0];
int column = coordinates[1];
ocean.shootAt(row, column);
availableSpot[row][column] = false;
isGameOver = ocean.isGameOver();
ocean.print();
print(3);
print(100);
}
//print info saying you win
print(4);
}
public static void main(String[] args) {
BattleshipGame battleshipGame = new BattleshipGame();
battleshipGame.play();
System.out.println("Continue? y/n");
Scanner sc = new Scanner(System.in);
String isPlay = sc.next();
while (isPlay.equals("y")){
battleshipGame = new BattleshipGame();
battleshipGame.play();
System.out.println("Continue? y/n");
isPlay = sc.next();
}
sc.close();
}
}
Ocean.java
package battleship;
import java.util.*;
public class Ocean {
private Ship[][] ships;
private int shotsFired;
private int hitCount;
private int shipsSunk;
Random random = new Random();
private boolean[][] shadow;
private Ship battleship;
private Ship cruiser1, cruiser2;
private Ship destroyer1, destroyer2, destroyer3;
private Ship submarine1, submarine2, submarine3, submarine4;
private ArrayList allShips;
//private boolean[][] shotLocations;
public Ocean() {
// TODO Auto-generated constructor stub
battleship = new Battleship();
cruiser1 = new Cruiser();
cruiser2 = new Cruiser();
destroyer1 = new Destroyer();
destroyer2 = new Destroyer();
destroyer3 = new Destroyer();
submarine1 = new Submarine();
submarine2 = new Submarine();
submarine3 = new Submarine();
submarine4 = new Submarine();
allShips = new ArrayList();
allShips.add(battleship);
allShips.add(cruiser1);
allShips.add(cruiser2);
allShips.add(destroyer1);
allShips.add(destroyer2);
allShips.add(destroyer3);
allShips.add(submarine1);
allShips.add(submarine2);
allShips.add(submarine3);
allShips.add(submarine4);
ships = new Ship[10][10];
shadow = new boolean[10][10];
//shotLocations = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
this.ships[i][j] = new EmptySea();
this.ships[i][j].setBowRow(i);
this.ships[i][j].setBowColumn(j);
this.ships[i][j].setHorizontal(true);
this.shadow[i][j] = false;
//this.shotLocations[i][j] = false;
}
}
this.shotsFired = 0;
this.hitCount = 0;
this.shipsSunk = 0;
}
public void placeAllShipsRandomly() {
int row;
int column;
int trueOrFalse;
for (Ship ship: allShips){
row = (int) (Math.random() * 10);
column = (int) (Math.random() * 10);
trueOrFalse = (int) (Math.random() * 2);
boolean horizontal = false;
if (trueOrFalse == 1) {
horizontal = true;
}
else {
horizontal = false;
}
while (!ship.okToPlaceShipAt(row, column, horizontal, this)) {
row = (int) (Math.random() * 10);
column = (int) (Math.random() * 10);
trueOrFalse = (int) (Math.random() * 2);
if (trueOrFalse == 1) {
horizontal = true;
}
else {
horizontal = false;
}
}
ship.placeShipAt(row, column, horizontal, this);
}
}
public boolean isOccupied(int row, int column) {
if (this.ships [row][column].getShipType().equals("empty")) {
return false;
}
return true;
}
public boolean shootAt(int row, int column) {
int hit = 0;
int sunkNum = 0;
if (isOccupied(row, column)&& !ships[row][column].isSunk()) {
this.hitCount += 1;
hit = 1;
}
this.shotsFired += 1;
//this.shotLocations[row][column] = true;
this.ships[row][column].shootAt(row, column);
for (Ship ship: this.allShips) {
if (ship.isSunk()){
sunkNum += 1;
}
}
this.shipsSunk = sunkNum;
if (hit == 1) {
return true;
}
return false;
}
public int getShotsFired() {
return this.shotsFired;
}
public int getHitCount() {
return this.hitCount;
}
public int getShipsSunk() {
return this.shipsSunk;
}
public boolean isGameOver() {
if (this.shipsSunk == 10) {
return true;
}
return false;
}
public Ship[][] getShipArray() {
return this.ships;
}
public void print() {
String s = " ";
int i;
int j;
for (i = -1; i < 10; i++) {
for (j = -1; j< 10; j++) {
if (i == -1){
if (j > -1){
s += " " + j;
}
}
else if (j == -1) {
s += i + " ";
}
else if (!this.isHit(i, j)) {
s += "." + " ";
}
else {
s += ships[i][j].toString() + " ";
}
}
s += " ";
}
System.out.println(s);
}
////////////////////////////////////////////////additional helper functions//////////////////////////
public boolean[][] getShadow() {
return this.shadow;
}
/**
* when put in one ship, shadow all its adjacent sea. Then the okToPrint function can make
judgment and forbid ships to place on the shadow.
*/
public void setShadow() {
for (int i = 0; i < 10 ; i++){
for (int j = 0; j < 10; j++) {
if (this.isOccupied(i,j)) {
for (int k = -1; k < 2; k++) {
for (int l = -1; l <2; l++ ) {
if ((i+k>=0) && (i+k<=9)&& (j+l>=0) && (j+l <=9)) {
shadow[i+k][j+l] = true;
}
}
}
}
}
}
}
/**
* setter for ship class to place ship in the ocean
* //param row
* //param column
* //param ship
*/
public void placeShip(int row, int column, Ship ship) {
this.ships[row][column] = ship;
//update the shadow(places which don't allow ship to be placed)
this.setShadow();
}
/**
* all ships list getter for testing
* //return
*/
public ArrayList getAllShips() {
return this.allShips;
}
public void printTest() {
String s = " ";
int i;
int j;
for (i = -1; i < 10; i++) {
for (j = -1; j< 10; j++) {
if (i == -1){
if (j > -1){
s += " " + j;
}
}
else if (j == -1) {
s += i + " ";
}
else if (!isOccupied(i,j)) {
s += "." + " ";
}
else {
s += ships[i][j].toString() + " ";
}
}
s += " ";
}
System.out.println(s);
}
public boolean isHit(int row, int column) {
Ship ship = this.ships[row][column];
int bowRow = ship.getBowRow();
int bowColumn = ship.getBowColumn();
//System.out.println(row + " " + column + " " + ship + " " + bowRow + " " +
bowColumn + ship.isHorizontal());
if (ship.getShipType().equals("empty")) {
return (ship.getHitArray()[0]);
}
else if (ship.isHorizontal()) {
if (ship.getHitArray()[column - bowColumn]) {
return true;
}
return false;
}
else {
if (ship.getHitArray()[row - bowRow]) {
return true;
}
return false;
}
}
}
Ship.java
package battleship;
public abstract class Ship {
private int bowRow;
private int bowColumn;
protected int length;
private boolean horizontal;
protected boolean[] hit = new boolean[4];
public Ship() {
// TODO Auto-generated constructor stub
super();
}
/**
* returns bowRow
* //return bowRow
*/
public int getBowRow() {
return bowRow;
}
public void setBowRow(int bowRow) {
this.bowRow = bowRow;
}
/**
* returns bowColumn
* //return bowColumn
*/
public int getBowColumn() {
return bowColumn;
}
/**
* sets the value of bowColumn
* //param bowColumn
*/
public void setBowColumn(int bowColumn) {
this.bowColumn = bowColumn;
}
/**
* returns the length of this particular ship
* //return length of the ship
*/
public int getLength() {
return length;
}
/**
* returns horizontal as boolean
* //return isHorizontal
*/
public boolean isHorizontal() {
return horizontal;
}
/**
* sets the value of instance variable horizontal
* //param horizontal
*/
public void setHorizontal(boolean horizontal) {
this.horizontal = horizontal;
}
abstract String getShipType();
/**
* returns true if it is okay to put a ship of certain length with its bow in this location, with the
given orientation
* returns false otherwise
* //param row
* //param column
* //param horizontal
* //param ocean
* //return okToPlaceShipAt as boolean
*/
public boolean okToPlaceShipAt(int row, int column, boolean horizontal, Ocean ocean){
boolean okToPlace = true;
boolean[][] shadows = ocean.getShadow();
if (horizontal){
for (int i=0; i9){okToPlace = false;}
else if (shadows[row][column+i]){okToPlace = false;}
}
}
else{
for (int i=0; i9){okToPlace = false;}
else if (shadows[row+i][column]){okToPlace = false;}
}
}
return okToPlace;
}
/**
* puts the ship on a certain spot in the ocean
* //param row
* //param column
* //param horizontal
* //param ocean
*/
public void placeShipAt(int row, int column, boolean horizontal, Ocean ocean){
this.setHorizontal(horizontal);
this.setBowRow(row);
this.setBowColumn(column);
if (!this.isHorizontal()){
for (int i=0;i
Solution
import java.util.Random;
import java.util.Scanner;
public class battleShip {
public static void main(String[] args) {
int[][] board = new int[2][2];
int[][] ships = new int[2][2];
int[] shoot = new int[2];
int attempts=0,
shotHit=0;
initBoard(board);
initShips(ships);
System.out.println();
do{
showBoard(board);
shoot(shoot);
attempts++;
if(hit(shoot,ships)){
hint(shoot,ships,attempts);
shotHit++;
}
else
hint(shoot,ships,attempts);
changeboard(shoot,ships,board);
}while(shotHit!=2);
System.out.println("   Battleship Java game finished! You hit 2 ships in "+attempts+"
attempts");
showBoard(board);
}
public static void initBoard(int[][] board){
for(int row=0 ; row < 2 ; row++ )
for(int column=0 ; column < 2 ; column++ )
board[row][column]=-1;
}
public static void showBoard(int[][] board){
System.out.println("t1 t2 t2 t4 t2");
System.out.println();
for(int row=0 ; row < 2 ; row++ ){
System.out.print((row+1)+"");
for(int column=0 ; column < 2 ; column++ ){
if(board[row][column]==-1){
System.out.print("t"+"~");
}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 initShips(int[][] ships){
Random random = new Random();
for(int ship=0 ; ship < 2 ; ship++){
ships[ship][0]=random.nextInt(2);
ships[ship][1]=random.nextInt(2);
//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 < ship ; last++){
if( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) )
do{
ships[ship][0]=random.nextInt(2);
ships[ship][1]=random.nextInt(2);
}while( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) );
}
}
}
public static void shoot(int[] shoot){
Scanner input = new Scanner(System.in);
System.out.print("Row: ");
shoot[0] = input.nextInt();
shoot[0]--;
System.out.print("Column: ");
shoot[1] = input.nextInt();
shoot[1]--;
}
public static boolean hit(int[] shoot, int[][] ships){
for(int ship=0 ; ship %d ships " +
"Column %d -> %d ships ",attempt,shoot[0]+1,row,shoot[1]+1,column);
}
public static void changeboard(int[] shoot, int[][] ships, int[][] board){
if(hit(shoot,ships))
board[shoot[0]][shoot[1]]=1;
else
board[shoot[0]][shoot[1]]=0;
}
}

More Related Content

Similar to The following code, is a one player battleship game in JAVA. Im tryi.pdf

Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdffeelinggifts
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docxKomlin1
 
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021Andrzej Jóźwiak
 
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...British Council
 
#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).docxPiersRCoThomsonw
 
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.pdffazalenterprises
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfasif1401
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfcontact32
 
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfNeed to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfflashfashioncasualwe
 
The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)Aaron Gustafson
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfkokah57440
 
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.pdfanithareadymade
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdffazilfootsteps
 

Similar to The following code, is a one player battleship game in JAVA. Im tryi.pdf (19)

Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdf
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
 
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
 
Include
IncludeInclude
Include
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Javascript
JavascriptJavascript
Javascript
 
#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
 
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
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdf
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfNeed to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
 
The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdf
 
Groovy
GroovyGroovy
Groovy
 
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
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
 

More from fonecomp

write a program that prompts the user to enter the center of a recta.pdf
write a program that prompts the user to enter the center of a recta.pdfwrite a program that prompts the user to enter the center of a recta.pdf
write a program that prompts the user to enter the center of a recta.pdffonecomp
 
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdf
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdfwrite 3 3 slide on China and Germany. Individual work (1) Choose a c.pdf
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdffonecomp
 
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdf
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdfWhy do negotiations fail O Conflicts are boring O Conflicts are co.pdf
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdffonecomp
 
What was the court-packing plan, and why is it sig- nificant to a.pdf
What was the court-packing plan, and why is it sig- nificant to a.pdfWhat was the court-packing plan, and why is it sig- nificant to a.pdf
What was the court-packing plan, and why is it sig- nificant to a.pdffonecomp
 
Who are the major stakeholders that Sony must consider when developi.pdf
Who are the major stakeholders that Sony must consider when developi.pdfWho are the major stakeholders that Sony must consider when developi.pdf
Who are the major stakeholders that Sony must consider when developi.pdffonecomp
 
What sort of prevention techniques would be useful when dealing with.pdf
What sort of prevention techniques would be useful when dealing with.pdfWhat sort of prevention techniques would be useful when dealing with.pdf
What sort of prevention techniques would be useful when dealing with.pdffonecomp
 
What are the main three types of organizational buyers How are they.pdf
What are the main three types of organizational buyers How are they.pdfWhat are the main three types of organizational buyers How are they.pdf
What are the main three types of organizational buyers How are they.pdffonecomp
 
Sharks are able to maintain their fluids hypertonic to the ocean env.pdf
Sharks are able to maintain their fluids hypertonic to the ocean env.pdfSharks are able to maintain their fluids hypertonic to the ocean env.pdf
Sharks are able to maintain their fluids hypertonic to the ocean env.pdffonecomp
 
Quantum Bank Inc. is a regional bank with branches throughout the so.pdf
Quantum Bank Inc. is a regional bank with branches throughout the so.pdfQuantum Bank Inc. is a regional bank with branches throughout the so.pdf
Quantum Bank Inc. is a regional bank with branches throughout the so.pdffonecomp
 
Neeb Corporation manufactures and sells a single product. The com.pdf
Neeb Corporation manufactures and sells a single product. The com.pdfNeeb Corporation manufactures and sells a single product. The com.pdf
Neeb Corporation manufactures and sells a single product. The com.pdffonecomp
 
Describe the primary, secondary, and tertiary structure of DNASo.pdf
Describe the primary, secondary, and tertiary structure of DNASo.pdfDescribe the primary, secondary, and tertiary structure of DNASo.pdf
Describe the primary, secondary, and tertiary structure of DNASo.pdffonecomp
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdffonecomp
 
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdf
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdfHarrison works in a cubicle at a window next to Karen Ravenwoods cu.pdf
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdffonecomp
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdffonecomp
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdffonecomp
 
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdf
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdfHow do the genomes of Archaea and Bacteria compare Drag and drop th.pdf
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdffonecomp
 
General question How would the technology affect who lives and who .pdf
General question How would the technology affect who lives and who .pdfGeneral question How would the technology affect who lives and who .pdf
General question How would the technology affect who lives and who .pdffonecomp
 
Describe how partial diploids can be produced in E. coli.Solutio.pdf
Describe how partial diploids can be produced in E. coli.Solutio.pdfDescribe how partial diploids can be produced in E. coli.Solutio.pdf
Describe how partial diploids can be produced in E. coli.Solutio.pdffonecomp
 
4.2Why is there waiting in an infinite-source queuing systemmul.pdf
4.2Why is there waiting in an infinite-source queuing systemmul.pdf4.2Why is there waiting in an infinite-source queuing systemmul.pdf
4.2Why is there waiting in an infinite-source queuing systemmul.pdffonecomp
 
A single layer of gold atoms lies on a table. The radius of each gol.pdf
A single layer of gold atoms lies on a table. The radius of each gol.pdfA single layer of gold atoms lies on a table. The radius of each gol.pdf
A single layer of gold atoms lies on a table. The radius of each gol.pdffonecomp
 

More from fonecomp (20)

write a program that prompts the user to enter the center of a recta.pdf
write a program that prompts the user to enter the center of a recta.pdfwrite a program that prompts the user to enter the center of a recta.pdf
write a program that prompts the user to enter the center of a recta.pdf
 
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdf
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdfwrite 3 3 slide on China and Germany. Individual work (1) Choose a c.pdf
write 3 3 slide on China and Germany. Individual work (1) Choose a c.pdf
 
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdf
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdfWhy do negotiations fail O Conflicts are boring O Conflicts are co.pdf
Why do negotiations fail O Conflicts are boring O Conflicts are co.pdf
 
What was the court-packing plan, and why is it sig- nificant to a.pdf
What was the court-packing plan, and why is it sig- nificant to a.pdfWhat was the court-packing plan, and why is it sig- nificant to a.pdf
What was the court-packing plan, and why is it sig- nificant to a.pdf
 
Who are the major stakeholders that Sony must consider when developi.pdf
Who are the major stakeholders that Sony must consider when developi.pdfWho are the major stakeholders that Sony must consider when developi.pdf
Who are the major stakeholders that Sony must consider when developi.pdf
 
What sort of prevention techniques would be useful when dealing with.pdf
What sort of prevention techniques would be useful when dealing with.pdfWhat sort of prevention techniques would be useful when dealing with.pdf
What sort of prevention techniques would be useful when dealing with.pdf
 
What are the main three types of organizational buyers How are they.pdf
What are the main three types of organizational buyers How are they.pdfWhat are the main three types of organizational buyers How are they.pdf
What are the main three types of organizational buyers How are they.pdf
 
Sharks are able to maintain their fluids hypertonic to the ocean env.pdf
Sharks are able to maintain their fluids hypertonic to the ocean env.pdfSharks are able to maintain their fluids hypertonic to the ocean env.pdf
Sharks are able to maintain their fluids hypertonic to the ocean env.pdf
 
Quantum Bank Inc. is a regional bank with branches throughout the so.pdf
Quantum Bank Inc. is a regional bank with branches throughout the so.pdfQuantum Bank Inc. is a regional bank with branches throughout the so.pdf
Quantum Bank Inc. is a regional bank with branches throughout the so.pdf
 
Neeb Corporation manufactures and sells a single product. The com.pdf
Neeb Corporation manufactures and sells a single product. The com.pdfNeeb Corporation manufactures and sells a single product. The com.pdf
Neeb Corporation manufactures and sells a single product. The com.pdf
 
Describe the primary, secondary, and tertiary structure of DNASo.pdf
Describe the primary, secondary, and tertiary structure of DNASo.pdfDescribe the primary, secondary, and tertiary structure of DNASo.pdf
Describe the primary, secondary, and tertiary structure of DNASo.pdf
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdf
 
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdf
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdfHarrison works in a cubicle at a window next to Karen Ravenwoods cu.pdf
Harrison works in a cubicle at a window next to Karen Ravenwoods cu.pdf
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdf
 
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdf
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdfHow do the genomes of Archaea and Bacteria compare Drag and drop th.pdf
How do the genomes of Archaea and Bacteria compare Drag and drop th.pdf
 
General question How would the technology affect who lives and who .pdf
General question How would the technology affect who lives and who .pdfGeneral question How would the technology affect who lives and who .pdf
General question How would the technology affect who lives and who .pdf
 
Describe how partial diploids can be produced in E. coli.Solutio.pdf
Describe how partial diploids can be produced in E. coli.Solutio.pdfDescribe how partial diploids can be produced in E. coli.Solutio.pdf
Describe how partial diploids can be produced in E. coli.Solutio.pdf
 
4.2Why is there waiting in an infinite-source queuing systemmul.pdf
4.2Why is there waiting in an infinite-source queuing systemmul.pdf4.2Why is there waiting in an infinite-source queuing systemmul.pdf
4.2Why is there waiting in an infinite-source queuing systemmul.pdf
 
A single layer of gold atoms lies on a table. The radius of each gol.pdf
A single layer of gold atoms lies on a table. The radius of each gol.pdfA single layer of gold atoms lies on a table. The radius of each gol.pdf
A single layer of gold atoms lies on a table. The radius of each gol.pdf
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 

The following code, is a one player battleship game in JAVA. Im tryi.pdf

  • 1. The following code, is a one player battleship game in JAVA. Im trying to Enhance the game to be a two player game (were a player plays aggainst a computer opponent). With TWO boards displayed side by side. The player and the computer must take turns selecting the coordinates on their own boards. (the ships cannot be placed adjacent to each other). BattleShipGame.java package battleship; import java.util.ArrayList; import java.util.Scanner; public class BattleshipGame { private Ocean ocean; private boolean[][] availableSpot; private Scanner sc; public BattleshipGame() { // define a new ocean and a new 2D array to store available coordinates ocean = new Ocean(); availableSpot = new boolean[10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++){ availableSpot[i][j] = true; } } } /** * prints the game menu and info * //param select */ public void print(int select){ String info; switch (select) { case 1: info = "Welcome to the World of Battleship!"; break; case 2: info = "Enter coordinates to fire: "; break; case 3: info = "Shots fired: "+ocean.getShotsFired()+", Ships sunk: "+ocean.getShipsSunk();
  • 2. break; case 4: info = "Congratulations! You win!"; break; case 99: info = "Invalid input. Please re-enter:"; break; case 100: info = "--------------------------------------------"; break; case 101: info = " ============================================"; break; default: info = "Error selection"; break; } System.out.println(info); } /** * check if the input is valid * //param input * //return boolean */ public boolean checkValidInput(String input){ ArrayList numList = new ArrayList(); for (int i=0;i<10;i++){ numList.add(""+i); } String[] coordinates = input.split(" "); //returns false if there are not 2 strings if (coordinates.length!=2){ return false; } //returns false if any of the strings is not a single digit number for (String str: coordinates){ if (numList.contains(str)==false){ return false; } } //returns false if the coordinates have already been shot at
  • 3. int row = Integer.parseInt(coordinates[0]); int column = Integer.parseInt(coordinates[1]); if (this.availableSpot[row][column]==false){ return false; } return true; } /** * get the coordinates to shoot at from the String input * //param input * //return int[] coordinates */ public int[] getCoordinates(String input){ int[] coordinates = new int[2]; String[] strList = input.split(" "); int row = Integer.parseInt(strList[0]); int column = Integer.parseInt(strList[1]); coordinates[0] = row; coordinates[1] = column; return coordinates; } /** * play the battleship game */ public void play(){ print(101); print(1); ocean.placeAllShipsRandomly(); boolean isGameOver = ocean.isGameOver(); sc = new Scanner(System.in); //print the ocean and start the game ocean.print(); print(3);
  • 4. while (!isGameOver){ print(2); String input = sc.nextLine(); //check if input is valid while (!checkValidInput(input)){ print(99); input = sc.nextLine(); } //get coordinates and fire int[] coordinates = getCoordinates(input); int row = coordinates[0]; int column = coordinates[1]; ocean.shootAt(row, column); availableSpot[row][column] = false; isGameOver = ocean.isGameOver(); ocean.print(); print(3); print(100); } //print info saying you win print(4); } public static void main(String[] args) { BattleshipGame battleshipGame = new BattleshipGame(); battleshipGame.play(); System.out.println("Continue? y/n"); Scanner sc = new Scanner(System.in); String isPlay = sc.next(); while (isPlay.equals("y")){ battleshipGame = new BattleshipGame(); battleshipGame.play(); System.out.println("Continue? y/n"); isPlay = sc.next();
  • 5. } sc.close(); } } Ocean.java package battleship; import java.util.*; public class Ocean { private Ship[][] ships; private int shotsFired; private int hitCount; private int shipsSunk; Random random = new Random(); private boolean[][] shadow; private Ship battleship; private Ship cruiser1, cruiser2; private Ship destroyer1, destroyer2, destroyer3; private Ship submarine1, submarine2, submarine3, submarine4; private ArrayList allShips; //private boolean[][] shotLocations; public Ocean() { // TODO Auto-generated constructor stub battleship = new Battleship(); cruiser1 = new Cruiser(); cruiser2 = new Cruiser(); destroyer1 = new Destroyer(); destroyer2 = new Destroyer(); destroyer3 = new Destroyer(); submarine1 = new Submarine(); submarine2 = new Submarine(); submarine3 = new Submarine(); submarine4 = new Submarine(); allShips = new ArrayList(); allShips.add(battleship); allShips.add(cruiser1);
  • 6. allShips.add(cruiser2); allShips.add(destroyer1); allShips.add(destroyer2); allShips.add(destroyer3); allShips.add(submarine1); allShips.add(submarine2); allShips.add(submarine3); allShips.add(submarine4); ships = new Ship[10][10]; shadow = new boolean[10][10]; //shotLocations = new boolean[10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { this.ships[i][j] = new EmptySea(); this.ships[i][j].setBowRow(i); this.ships[i][j].setBowColumn(j); this.ships[i][j].setHorizontal(true); this.shadow[i][j] = false; //this.shotLocations[i][j] = false; } } this.shotsFired = 0; this.hitCount = 0; this.shipsSunk = 0; } public void placeAllShipsRandomly() { int row; int column; int trueOrFalse; for (Ship ship: allShips){ row = (int) (Math.random() * 10); column = (int) (Math.random() * 10); trueOrFalse = (int) (Math.random() * 2); boolean horizontal = false; if (trueOrFalse == 1) {
  • 7. horizontal = true; } else { horizontal = false; } while (!ship.okToPlaceShipAt(row, column, horizontal, this)) { row = (int) (Math.random() * 10); column = (int) (Math.random() * 10); trueOrFalse = (int) (Math.random() * 2); if (trueOrFalse == 1) { horizontal = true; } else { horizontal = false; } } ship.placeShipAt(row, column, horizontal, this); } } public boolean isOccupied(int row, int column) { if (this.ships [row][column].getShipType().equals("empty")) { return false; } return true; } public boolean shootAt(int row, int column) { int hit = 0; int sunkNum = 0; if (isOccupied(row, column)&& !ships[row][column].isSunk()) { this.hitCount += 1; hit = 1; } this.shotsFired += 1; //this.shotLocations[row][column] = true; this.ships[row][column].shootAt(row, column); for (Ship ship: this.allShips) {
  • 8. if (ship.isSunk()){ sunkNum += 1; } } this.shipsSunk = sunkNum; if (hit == 1) { return true; } return false; } public int getShotsFired() { return this.shotsFired; } public int getHitCount() { return this.hitCount; } public int getShipsSunk() { return this.shipsSunk; } public boolean isGameOver() { if (this.shipsSunk == 10) { return true; } return false; } public Ship[][] getShipArray() { return this.ships; } public void print() { String s = " "; int i; int j; for (i = -1; i < 10; i++) { for (j = -1; j< 10; j++) { if (i == -1){ if (j > -1){
  • 9. s += " " + j; } } else if (j == -1) { s += i + " "; } else if (!this.isHit(i, j)) { s += "." + " "; } else { s += ships[i][j].toString() + " "; } } s += " "; } System.out.println(s); } ////////////////////////////////////////////////additional helper functions////////////////////////// public boolean[][] getShadow() { return this.shadow; } /** * when put in one ship, shadow all its adjacent sea. Then the okToPrint function can make judgment and forbid ships to place on the shadow. */ public void setShadow() { for (int i = 0; i < 10 ; i++){ for (int j = 0; j < 10; j++) { if (this.isOccupied(i,j)) { for (int k = -1; k < 2; k++) { for (int l = -1; l <2; l++ ) { if ((i+k>=0) && (i+k<=9)&& (j+l>=0) && (j+l <=9)) { shadow[i+k][j+l] = true; } }
  • 10. } } } } } /** * setter for ship class to place ship in the ocean * //param row * //param column * //param ship */ public void placeShip(int row, int column, Ship ship) { this.ships[row][column] = ship; //update the shadow(places which don't allow ship to be placed) this.setShadow(); } /** * all ships list getter for testing * //return */ public ArrayList getAllShips() { return this.allShips; } public void printTest() { String s = " "; int i; int j; for (i = -1; i < 10; i++) { for (j = -1; j< 10; j++) { if (i == -1){ if (j > -1){ s += " " + j; } } else if (j == -1) { s += i + " ";
  • 11. } else if (!isOccupied(i,j)) { s += "." + " "; } else { s += ships[i][j].toString() + " "; } } s += " "; } System.out.println(s); } public boolean isHit(int row, int column) { Ship ship = this.ships[row][column]; int bowRow = ship.getBowRow(); int bowColumn = ship.getBowColumn(); //System.out.println(row + " " + column + " " + ship + " " + bowRow + " " + bowColumn + ship.isHorizontal()); if (ship.getShipType().equals("empty")) { return (ship.getHitArray()[0]); } else if (ship.isHorizontal()) { if (ship.getHitArray()[column - bowColumn]) { return true; } return false; } else { if (ship.getHitArray()[row - bowRow]) { return true; } return false; } }
  • 12. } Ship.java package battleship; public abstract class Ship { private int bowRow; private int bowColumn; protected int length; private boolean horizontal; protected boolean[] hit = new boolean[4]; public Ship() { // TODO Auto-generated constructor stub super(); } /** * returns bowRow * //return bowRow */ public int getBowRow() { return bowRow; } public void setBowRow(int bowRow) { this.bowRow = bowRow; } /** * returns bowColumn * //return bowColumn */ public int getBowColumn() { return bowColumn; } /** * sets the value of bowColumn * //param bowColumn */ public void setBowColumn(int bowColumn) { this.bowColumn = bowColumn;
  • 13. } /** * returns the length of this particular ship * //return length of the ship */ public int getLength() { return length; } /** * returns horizontal as boolean * //return isHorizontal */ public boolean isHorizontal() { return horizontal; } /** * sets the value of instance variable horizontal * //param horizontal */ public void setHorizontal(boolean horizontal) { this.horizontal = horizontal; } abstract String getShipType(); /** * returns true if it is okay to put a ship of certain length with its bow in this location, with the given orientation * returns false otherwise * //param row * //param column * //param horizontal * //param ocean * //return okToPlaceShipAt as boolean */ public boolean okToPlaceShipAt(int row, int column, boolean horizontal, Ocean ocean){
  • 14. boolean okToPlace = true; boolean[][] shadows = ocean.getShadow(); if (horizontal){ for (int i=0; i9){okToPlace = false;} else if (shadows[row][column+i]){okToPlace = false;} } } else{ for (int i=0; i9){okToPlace = false;} else if (shadows[row+i][column]){okToPlace = false;} } } return okToPlace; } /** * puts the ship on a certain spot in the ocean * //param row * //param column * //param horizontal * //param ocean */ public void placeShipAt(int row, int column, boolean horizontal, Ocean ocean){ this.setHorizontal(horizontal); this.setBowRow(row); this.setBowColumn(column); if (!this.isHorizontal()){ for (int i=0;i Solution import java.util.Random; import java.util.Scanner; public class battleShip { public static void main(String[] args) { int[][] board = new int[2][2]; int[][] ships = new int[2][2]; int[] shoot = new int[2];
  • 15. int attempts=0, shotHit=0; initBoard(board); initShips(ships); System.out.println(); do{ showBoard(board); shoot(shoot); attempts++; if(hit(shoot,ships)){ hint(shoot,ships,attempts); shotHit++; } else hint(shoot,ships,attempts); changeboard(shoot,ships,board); }while(shotHit!=2); System.out.println(" Battleship Java game finished! You hit 2 ships in "+attempts+" attempts"); showBoard(board); } public static void initBoard(int[][] board){ for(int row=0 ; row < 2 ; row++ ) for(int column=0 ; column < 2 ; column++ ) board[row][column]=-1; } public static void showBoard(int[][] board){
  • 16. System.out.println("t1 t2 t2 t4 t2"); System.out.println(); for(int row=0 ; row < 2 ; row++ ){ System.out.print((row+1)+""); for(int column=0 ; column < 2 ; column++ ){ if(board[row][column]==-1){ System.out.print("t"+"~"); }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 initShips(int[][] ships){ Random random = new Random(); for(int ship=0 ; ship < 2 ; ship++){ ships[ship][0]=random.nextInt(2); ships[ship][1]=random.nextInt(2); //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 < ship ; last++){ if( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) ) do{ ships[ship][0]=random.nextInt(2); ships[ship][1]=random.nextInt(2); }while( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) ); } }
  • 17. } public static void shoot(int[] shoot){ Scanner input = new Scanner(System.in); System.out.print("Row: "); shoot[0] = input.nextInt(); shoot[0]--; System.out.print("Column: "); shoot[1] = input.nextInt(); shoot[1]--; } public static boolean hit(int[] shoot, int[][] ships){ for(int ship=0 ; ship %d ships " + "Column %d -> %d ships ",attempt,shoot[0]+1,row,shoot[1]+1,column); } public static void changeboard(int[] shoot, int[][] ships, int[][] board){ if(hit(shoot,ships)) board[shoot[0]][shoot[1]]=1; else board[shoot[0]][shoot[1]]=0; } }