Ad

In Node.js How Do I Access A Function From App.js That Is In A Module That Is In Another Module?

- 1 answer

I am creating a battleship game to learn node.js. In the app.js file I create two players based on a module called Users which imports a module called Board. Inside the Board module I have a function named placeShip. How can I access this placeShip function from app.js? As it is I get a TypeError: Player1.placeShip is not a function.

Users module:

var User = function() {
var board = require('./Board');
return {
    Username: "",
    Gender: "",
    Player: "",
    Turn: "",
    Ships: {
        Carrier: ['C','C','C','C','C'],
        Battleship: ['B','B','B','B'],
        Cruiser: ['Z','Z','Z'],
        Submarine: ['S','S','S'],
        Destroyer: ['D','D']
    },
    Board: new board,
    Hit: function (ship,position) {
        var x = this.Ships[ship][position];
        if(x != null && x != undefined) {
            this.Ships[ship][position] = 'X';
        }
    },
    OutputAll: function () {
        for (var item in this) {
            if (item == "Ships") {
                console.log("Ships: ");
                for (var ship in this.Ships) {
                    console.log("    " + ship + ": " + this.Ships[ship]);
                }
            } else if(item != "Hit" && item != "OutputAll" && item != "Board") {
                console.log(item + ": " + this[item]);
            }
        }
    }
}
}

module.exports = User;

Board module:

var GameBoard = function() {
return {
    Yours: createArray(10),

    Mine: createArray(10),

    ClearBoards: function () {
        this.Yours = createArray(10);
        this.Mine = createArray(10);
    },

    DisplayBoard: function(board){
        for(var i in board){
            console.log(board[i]);
        }
    }
}
}

function createArray(length) {
var table = new Array(length);

for (var i = 0; i < length; i++) {
    table[i] = new Array(length);
    // Make each space a 0
    for (var row = 0; row < length; row++) {
        table[i][row] = 0;
    }
}
return table;
}

function placeShip(ship,rowStart,rowEnd,colStart,colEnd) {
var letter;

//=====Get Ship Letter======
for (x = 0; x < ship.length; x++) {
    if (ship[x] != 'X') {
        letter = ship[x];
        break;
    }
}

//=====Get Orientation=======
// Ship is horizontal
if (rowStart === rowEnd) {
    // Put the ship letter where it lies
    for (x = colStart; x <= colEnd; x++) {
        this.Board.Mine[rowStart][x] = letter;
    }
}
// Or Ship is vertical
else if (colStart === colEnd) {
    // Put the ship letter where it lies
    for (x = rowStart; x <= rowEnd; x++) {
        this.Board.Mine[x][colStart] = letter;
    }
}
// Or Ship is diagonal
else {
    // Put the ship letter where it lies
    this.Board.Mine[rowStart][colStart] = letter;
    for (x = 0; x < ship.length; x++) {
        this.Board.Mine[rowStart + 1][colStart + 1] = letter;
    }
}
}

module.exports = GameBoard;
module.exports.placeShip = placeShip; 

app.js:

var http = require('http');
var fs = require('fs');
var Users = require('./public/Scripts/Users');

var Player1 = new Users;
var Player2 = new Users;

// When a user navigates to the site
function onRequest(request, response){
console.log("User made a " + request.method + " request from " + request.url);

Player1.Username = "Jamie";
Player1.Hit("Carrier", 4);
console.log("Player 1 Board:========");
Player1.Board.DisplayBoard(Player1.Board.Mine);
Player1.placeShip(Player1.Ships.Carrier,0,4,0,0);
Player1.Board.DisplayBoard(Player1.Board.Mine);


console.log("Player 2 Board:========");
Player2.Username = "Kimyl";
Player2.Board.DisplayBoard(Player2.Board.Yours);
console.log("Player 1: " + Player1.OutputAll());
console.log("Player 2: " + Player2.OutputAll());

// If user asks for the home page
if(request.method == 'GET' && request.url == '/' ) {
    console.log('Successfully requested Home Page');

    // Write a header response
    response.writeHead(200, {"Content-Type": "text/html"});

    fs.createReadStream("./public/index.html").pipe(response);
} else{
    send404Error(response);
}
}

// 404 Error
function send404Error(response){
// Write a header response
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("The page you are looking for could not be found!");
response.end();
}

http.createServer(onRequest).listen(3000);
console.log("Server running...");
Ad

Answer

We need to use the board module in the User module , so the best way is to pass the board module as a parameter to User and require both in the main file app.js

app.js:

var board = require("./public/scripts/board");
var Users  = require("./public/scripts/Users")(board);

Users module

var User = function(board){
  return{
    Board: new board;
  }
}

Move the placeShip function inside of the Board function and change your this.Board.Mine to this.Mine

Ad
source: stackoverflow.com
Ad