0% found this document useful (0 votes)
11 views4 pages

BattleShipGame Explanation

Uploaded by

Yeabisra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

BattleShipGame Explanation

Uploaded by

Yeabisra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Explanation of BattleShipGame Code

import java.util.Random;

Imports the `Random` class to generate random numbers.

import java.util.Scanner;

Imports the `Scanner` class to read input from the user.

public class BattelShipGame {

Defines the `BattelShipGame` class for the game logic.

public static Random rnd = new Random();

Declares a static random object for generating random values.

private int sizeOfGrid = 7;

Sets the default grid size to 7x7.

private int sizeOfship = 3;

Sets the default ship size to 3 cells.

private int numOfShip = 3;

Sets the default number of ships to 3.


private int[][] grid = new int[sizeOfGrid][sizeOfGrid];

Initializes the game grid as a 2D array.

private Ship[] battleShips = new Ship[numOfShip];

Creates an array to store the ships.

private boolean[] sankShips = new boolean[numOfShip];

Tracks whether each ship is sunk.

private int score = sizeOfGrid * sizeOfGrid;

Initializes the score to the total number of grid cells.

BattelShipGame() { this.initGrid(); }

Default constructor that initializes the grid.

BattelShipGame(int numOfShip) { this.numOfShip = numOfShip; this.initGrid(); }

Constructor allowing customization of the number of ships.

BattelShipGame(int sizeOfGrid, int sizeOfship, int numOfShip) {

Constructor allowing customization of grid size, ship size, and number of ships.
private void initGrid() {

Initializes the grid, ships, and places them randomly.

public int getScore() { return score; }

Returns the current score.

private void markLocation(int[][] nloc) {

Marks ship locations on the grid.

private boolean takenLocation(int[][] nl) {

Checks if a location is already occupied.

public int[][] newlocation() {

Generates a new random location for a ship.

void printgrid() {

Displays the game grid to the player.

public int playGame() {

Handles the main gameplay mechanics.


public void resetGame() { this.initGrid(); }

Resets the game for a new round.

You might also like