Question

The battleship game uses a 10x10 playing board   with node Js There are 5 ship Migrate...

The battleship game uses a 10x10 playing board   with node Js There are 5 ship Migrate the local array of the game board to any array in NodeJS on the server and make a request to create the random board - start a new game

0 0
Add a comment Improve this question Transcribed image text
Answer #1

var Settings = require('./settings.js');

var GameStatus = require('./gameStatus.js');

/**

* BattleshipGame constructor

* @param {type} id Game ID

* @param {type} idPlayer1 Socket ID of player 1

* @param {type} idPlayer2 Socket ID of player 2

*/

function BattleshipGame(id, idPlayer1, idPlayer2) {

this.id = id;

this.currentPlayer = Math.floor(Math.random() * 2);

this.winningPlayer = null;

this.gameStatus = GameStatus.inProgress;

this.players = [new Player(idPlayer1), new Player(idPlayer2)];

}

/**

* Get socket ID of player

* @param {type} player

* @returns {undefined}

*/

BattleshipGame.prototype.getPlayerId = function(player) {

  return this.players[player].id;

};

/**

* Get socket ID of winning player

* @returns {BattleshipGame.prototype@arr;players@pro;id}

*/

BattleshipGame.prototype.getWinnerId = function() {

if(this.winningPlayer === null) {

    return null;

}

return this.players[this.winningPlayer].id;

};

/**

* Get socket ID of losing player

* @returns {BattleshipGame.prototype@arr;players@pro;id}

*/

BattleshipGame.prototype.getLoserId = function() {

if(this.winningPlayer === null) {

    return null;

}

var loser = this.winningPlayer === 0 ? 1 : 0;

return this.players[loser].id;

};

/**

* Switch turns

*/

BattleshipGame.prototype.switchPlayer = function() {

this.currentPlayer = this.currentPlayer === 0 ? 1 : 0;

};

/**

* Abort game

* @param {Number} player Player who made the request

*/

BattleshipGame.prototype.abortGame = function(player) {

// give win to opponent

this.gameStatus = GameStatus.gameOver;

this.winningPlayer = player === 0 ? 1 : 0;

}

/**

* Fire shot for current player

* @param {Object} position with x and y

* @returns {boolean} True if shot was valid

*/

BattleshipGame.prototype.shoot = function(position) {

var opponent = this.currentPlayer === 0 ? 1 : 0,

      gridIndex = position.y * Settings.gridCols + position.x;

if(this.players[opponent].shots[gridIndex] === 0 && this.gameStatus === GameStatus.inProgress) {

    // Square has not been shot at yet.

    if(!this.players[opponent].shoot(gridIndex)) {

      // Miss

      this.switchPlayer();

    }

    // Check if game over

    if(this.players[opponent].getShipsLeft() <= 0) {

      this.gameStatus = GameStatus.gameOver;

      this.winningPlayer = opponent === 0 ? 1 : 0;

    }   

    return true;

}

return false;

};

/**

* Get game state update (for one grid).

* @param {Number} player Player who is getting this update

* @param {Number} gridOwner Player whose grid state to update

* @returns {BattleshipGame.prototype.getGameState.battleshipGameAnonym$0}

*/

BattleshipGame.prototype.getGameState = function(player, gridOwner) {

return {

    turn: this.currentPlayer === player,                 // is it this player's turn?

    gridIndex: player === gridOwner ? 0 : 1,             // which client grid to update (0 = own, 1 = opponent)

    grid: this.getGrid(gridOwner, player !== gridOwner) // hide unsunk ships if this is not own grid

};

};

/**

* Get grid with ships for a player.

* @param {type} player Which player's grid to get

* @param {type} hideShips Hide unsunk ships

* @returns {BattleshipGame.prototype.getGridState.battleshipGameAnonym$0}

*/

BattleshipGame.prototype.getGrid = function(player, hideShips) {

return {

    shots: this.players[player].shots,

    ships: hideShips ? this.players[player].getSunkShips() : this.players[player].ships

};

};

module.exports = BattleshipGame;

module.exports = {

inProgress: 1,

gameOver: 2

};

var Ship = require('./ship.js');

var Settings = require('./settings.js');

/**

* Player constructor

* @param {type} id Socket ID

*/

function Player(id) {

var i;

this.id = id;

this.shots = Array(Settings.gridRows * Settings.gridCols);

this.shipGrid = Array(Settings.gridRows * Settings.gridCols);

this.ships = [];

for(i = 0; i < Settings.gridRows * Settings.gridCols; i++) {

    this.shots[i] = 0;

    this.shipGrid[i] = -1;

}

if(!this.createRandomShips()) {

    // Random placement of ships failed. Use fallback layout (should rarely happen).

    this.ships = [];

    this.createShips();

}

};

/**

* Fire shot on grid

* @param {type} gridIndex

* @returns {Boolean} True if hit

*/

Player.prototype.shoot = function(gridIndex) {

if(this.shipGrid[gridIndex] >= 0) {

    // Hit!

    this.ships[this.shipGrid[gridIndex]].hits++;

    this.shots[gridIndex] = 2;

    return true;

} else {

    // Miss

    this.shots[gridIndex] = 1;

    return false;

}

};

/**

* Get an array of sunk ships

* @returns {undefined}

*/

Player.prototype.getSunkShips = function() {

var i, sunkShips = [];

for(i = 0; i < this.ships.length; i++) {

    if(this.ships[i].isSunk()) {

      sunkShips.push(this.ships[i]);

    }

}

return sunkShips;

};

/**

* Get the number of ships left

* @returns {Number} Number of ships left

*/

Player.prototype.getShipsLeft = function() {

var i, shipCount = 0;

for(i = 0; i < this.ships.length; i++) {

    if(!this.ships[i].isSunk()) {

      shipCount++;

    }

}

return shipCount;

}

/**

* Create ships and place them randomly in grid

* @returns {Boolean}

*/

Player.prototype.createRandomShips = function() {

var shipIndex;

for(shipIndex = 0; shipIndex < Settings.ships.length; shipIndex++) {

    ship = new Ship(Settings.ships[shipIndex]);

    if(!this.placeShipRandom(ship, shipIndex)) {

      return false;

    }

    this.ships.push(ship);

}

return true;

};

/**

* Try to place a ship randomly in grid without overlapping another ship.

* @param {Ship} ship

* @param {Number} shipIndex

* @returns {Boolean}

*/

Player.prototype.placeShipRandom = function(ship, shipIndex) {

var i, j, gridIndex, xMax, yMax, tryMax = 25;

for(i = 0; i < tryMax; i++) {

    ship.horizontal = Math.random() < 0.5;

    xMax = ship.horizontal ? Settings.gridCols - ship.size + 1 : Settings.gridCols;

    yMax = ship.horizontal ? Settings.gridRows : Settings.gridRows - ship.size + 1;

    ship.x = Math.floor(Math.random() * xMax);

    ship.y = Math.floor(Math.random() * yMax);

    if(!this.checkShipOverlap(ship) && !this.checkShipAdjacent(ship)) {

      // success - ship does not overlap or is adjacent to other ships

      // place ship array-index in shipGrid

      gridIndex = ship.y * Settings.gridCols + ship.x;

      for(j = 0; j < ship.size; j++) {

        this.shipGrid[gridIndex] = shipIndex;

        gridIndex += ship.horizontal ? 1 : Settings.gridCols;

      }

      return true;

    }

}

return false;

}

/**

* Check if a ship overlaps another ship in the grid.

* @param {Ship} ship

* @returns {Boolean} True if ship overlaps

*/

Player.prototype.checkShipOverlap = function(ship) {

var i, gridIndex = ship.y * Settings.gridCols + ship.x;

for(i = 0; i < ship.size; i++) {

    if(this.shipGrid[gridIndex] >= 0) {

      return true;

    }

    gridIndex += ship.horizontal ? 1 : Settings.gridCols;

}

return false;

}

/**

* Check if there are ships adjacent to this ship placement

* @param {Ship} ship

* @returns {Boolean} True if adjacent ship found

*/

Player.prototype.checkShipAdjacent = function(ship) {

var i, j,

      x1 = ship.x - 1,

      y1 = ship.y - 1,

      x2 = ship.horizontal ? ship.x + ship.size : ship.x + 1,

      y2 = ship.horizontal ? ship.y + 1 : ship.y + ship.size;

for(i = x1; i <= x2; i++) {

    if(i < 0 || i > Settings.gridCols - 1) continue;

    for(j = y1; j <= y2; j++) {

      if(j < 0 || j > Settings.gridRows - 1) continue;

      if(this.shipGrid[j * Settings.gridCols + i] >= 0) {

        return true;

      }

    }

}

return false;

}

/**

* Create ships and place them in grid in a prearranged layout

*/

Player.prototype.createShips = function() {

var shipIndex, i, gridIndex, ship,

      x = [1, 3, 5, 8, 8], y = [1, 2, 5, 2, 8],

      horizontal = [false, true, false, false, true];

for(shipIndex = 0; shipIndex < Settings.ships.length; shipIndex++) {

    ship = new Ship(Settings.ships[shipIndex]);

    ship.horizontal = horizontal[shipIndex];

    ship.x = x[shipIndex];

    ship.y = y[shipIndex];

    // place ship array-index in shipGrid

    gridIndex = ship.y * Settings.gridCols + ship.x;

    for(i = 0; i < ship.size; i++) {

      this.shipGrid[gridIndex] = shipIndex;

      gridIndex += ship.horizontal ? 1 : Settings.gridCols;

    }

    this.ships.push(ship);

}

};

module.exports = Player;

module.exports = {

gridRows: 10,

gridCols: 10,

ships: [ 5, 4, 3, 3, 2 ]

};

/**

* Ship constructor

* @param {Number} size

*/

function Ship(size) {

this.x = 0;

this.y = 0;

this.size = size;

this.hits = 0;

this.horizontal = false;

}

/**

* Check if ship is sunk

* @returns {Boolean}

*/

Ship.prototype.isSunk = function() {

return this.hits >= this.size;

};

module.exports = Ship;

Add a comment
Know the answer?
Add Answer to:
The battleship game uses a 10x10 playing board   with node Js There are 5 ship Migrate...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next...

    Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next two assignments you will be creating a one-player version of the game. The game is extremely simple. Each player arranges a fleet of ships in a grid. The grid is hidden from the opponent. Here is an ASCII representation of a 10x10 grid. The ‘X’s represent ships, the ‘~’s represent empty water. There are three ships in the picture: A vertical ship with a...

  • For your Project, you will develop a simple battleship game. Battleship is a guessing game for...

    For your Project, you will develop a simple battleship game. Battleship is a guessing game for two players. It is played on four grids. Two grids (one for each player) are used to mark each players' fleets of ships (including battleships). The locations of the fleet (these first two grids) are concealed from the other player so that they do not know the locations of the opponent’s ships. Players alternate turns by ‘firing torpedoes’ at the other player's ships. The...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the o...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • In C++ program use the new style od C++ not the old one. Simple Battleship You...

    In C++ program use the new style od C++ not the old one. Simple Battleship You will make a game similar to the classic board game Battleship. You will set up a 5 x 5, 2 dimensional array. In that array, you will use a random number generator to select 5 elements that will act as the placeholders for your "battleships". Your user will get 10 guesses to "seek and destroy" the battleships. After their 10 guesses, you will tell...

  • C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The...

    C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The game is played on an NxN grid. Each player will place a specified collection of ships: The ships will vary in length (size) from 2 to 5; There can be any number or any size ship. There may be no ships of a particular size; EXCEPT the battleship – which there will always be 1 and only 1. Player order will be random but...

  • Write a Java program to play the game Tic-Tac-Toe. Start off with a human playing a...

    Write a Java program to play the game Tic-Tac-Toe. Start off with a human playing a human, so each player makes their own moves. Follow the design below, creating the methods indicated and invoking them in the main program. Use a char array of size 9 as the board; initialize with the characters 0 to 8 so that it starts out looking something like the board on the left. 0|1|2 3|4|5 6|7|8 and then as moves are entered the board...

  • INTRODUCTION: Play sorry with two die, and one peg. Move your piece down the board first....

    INTRODUCTION: Play sorry with two die, and one peg. Move your piece down the board first. But rolling certain numbers will change the pace of the game. INCLUDE IN YOUR ASSIGNMENT: Annotation is a major part of any program. At the top of each of your C++ programs, you should have at least four lines of documentation: // Program name: tictactoe.cpp // Author: Twilight Sparkle // Date last updated: 5/26/2016 // Purpose: Play the game of Tic-Tac-Toe ASSIGNMENT: Sorry Game...

  • War—A Card game Playing cards are used in many computer games, including versions of such classic...

    War—A Card game Playing cards are used in many computer games, including versions of such classics as solitaire, hearts, and poker. War:    Deal two Cards—one for the computer and one for the player—and determine the higher card, then display a message indicating whether the cards are equal, the computer won, or the player won. (Playing cards are considered equal when they have the same value, no matter what their suit is.) For this game, assume the Ace (value 1) is...

  • Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every...

    Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every part, and include java doc and comments Create a battleship program. Include Javadoc and comments. Grade 12 level coding style using java only. You will need to create a Ship class, Location class, Grid Class, Add a ship to the Grid, Create the Player class, the Battleship class, Add at least one extension. Make sure to include the testers. Starting code/ sample/methods will be...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT