使用node.js更正模块组织

时间:2015-09-17 13:37:30

标签: javascript node.js module

我用简单的JavaScript构建了一个小型国际象棋游戏,为了处理导入,我把它们全部推送到html文件中,给我以下内容:

game.html

.
.
<body id="body">
    <script src="scripts/utils.js"></script>
    <script src="scripts/pieces.js"></script>
    .
    .
    .
    <script src="scripts/game.js"></script>
</body>
</html>

现在我开始使用Node.js并希望移动逻辑服务器端并使用导入正确构建它,但是有两个文件我遇到了麻烦。第一个是

utils.js

function getEnemy(player) {
    return player===WHITE? BLACK : WHITE;
}

/**
 * A generator to generate pieces from given fen and return them all in an array.
 */
function generatePieces(fen) {

    var piece_array = [];
    var ranks = fen.split(' ')[0].split('/');
    for (var i=0; i < ranks.length; i++) {

        var squares = ranks[i];
        var rank = 8 - i;
        var file = 1; // keeping track of the current file.
        for (var j=0; j < squares.length; j++) {
            if (Number(squares[j])) {
                file += Number(squares[j]);
                continue;
            }
            var color = (squares[j] === squares[j].toUpperCase()? WHITE : BLACK);
            piece_array.push( generatePiece(squares[j], color, file, rank));
            file +=1;
        }
    }
    return piece_array;
}
function generatePiece(type, color, file, rank) {

    var square = new Square(file, rank);
    type = type.toUpperCase();
    switch(type) {
        case PAWN:
            return new Pawn(square, color);
        case KNIGHT:
            return new Knight(square, color);
        case KING:
            return new King(square, color);
        case BISHOP:
            return new Bishop(square, color);
        case ROOK:
            return new Rook(square, color);
        case QUEEN:
            return new Queen(square, color);
    }
}

/**
 * generates a square from the first two numbers in an array.
 * no validations are made.
 * @param position_array an array whose first two elements are numbers.
 * @returns {Square} a square with file equal to the first element and rank the second.
 */
function getSquareFromArray(position_array) {
    return new Square(position_array[0], position_array[1]);
}

/******* Square class
 * square object to encapsulate all these ugly arrays.
 * @param file file of the new square.
 * @param rank rank of the new square.
 */
function Square(file, rank) {
    this.file = file;
    this.rank = rank;

    /**
     * Checks if two squares have the same file and rank.
     * @param other another square
     * @returns {boolean} true if both squares are of the same position on the board.
     */
    this.equals = function(other) {
       return (this.file === other.file && this.rank === other.rank);
    };

    /**
     * Returns a string version of the square, formatted as "file rank".
     * @returns {string} string version of the square.
     */
    this.toString = function() {
        return String(file) + ' ' + String(rank);
    };


    /**
     * returns a new square with the given file and rank added to this square's file and rank.
     * @param file file to move the square
     * @param rank rank to move the square
     * @returns {Square}
     */
    this.getSquareAtOffset = function(file, rank) {
        file = Number(file)? file : 0;
        rank = Number(rank)? rank : 0;
        return new Square(this.file + file, this.rank + rank);
    };
}

/**
 * creates a new square object from a string of format '%d $d'
 * @param string string in format '%d %d'
 * returns square object
 */
function getSquareFromKey(string) {
    values = string.split(' ');
    return new Square(Number(values[0]), Number(values[1]));
}
/******* Move object
 * Move object to encapsulate a single game move.
 * Might be a bit of an overkill, but I prefer an array of moves over an array of arrays of squares.
 * @param from A square to move from.
 * @param to A square to move to.
 */
function Move(from, to) {
    this.from = from;
    this.to = to;
}

/******* SpecialMove object
 * Move object to encapsulate a single game move.
 * Might be a bit of an overkill, but I prefer an array of moves over an array of arrays of squares.
 * @param moves array of moves to make
 * @param removes array of squares to remove pieces from
 * @param insertions array of triplets, square to insert, wanted piece type, and piece color.
 */
function SpecialMove(moves, removes, insertions) {
    this.moves = moves? moves : [];
    this.removes = removes? removes : [];
    this.insertions = insertions? insertions : [];
}

我不确定如何正确导出。如果我将每个函数/对象分别添加到module.exports然后使用这个模块(几乎是任何其他对象)我的每个对象,我需要做this.utils = require('./utils');之类的事情,然后调用,例如, square = new this.utils.Square(file, rank);,这似乎不是一个好的解决方案。是否有更好的方式在全球范围内导入此文件?

第二个是不同类型作品的对象列表  的 pieces.js

var WHITE = 'w';
var BLACK = 'b';

var PAWN = 'P';
var KNIGHT = 'N';
var KING = 'K';
var BISHOP = 'B';
var ROOK = 'R';
var QUEEN = 'Q';

/********* Piece class
 * The parent class of all piece types.
 * @param square square of the piece.
 * @param color color of the piece, should be either 'white' or 'black'.
 * @constructor
 */
function Piece(square, color) {
    this.square = square;
    this.color = color;
}

/**
 * Returns the path the piece needs in order to get to the given square, if it's not a capture.
 * Returns null if the piece can't reach the square in one move.
 * @param to target square.
 */

Piece.prototype.getPath = function(to) {
    return null;
};

/**
 * Returns the path the piece needs in order to capture in the given square.
 * Returns null if the piece can't reach the square in one move.
 * Implement this if the piece captures in a different way then moving (i.e. a pawn);
 * @param to target square.
 */

Piece.prototype.getCapturePath = function(to) {
    return this.getPath(to);
};

/**
 * Compares the square of the piece with given square
 * @returns {boolean} if the piece is at the given square.
 */

Piece.prototype.isAt= function(square) {
  return (this.square.equals(square));
};

/******* Pawn class
 * Holds the movement of the pawn, refer to Piece for explanations.
 * @type {Piece}
 */
Pawn.prototype = Object.create(Piece.prototype);
Pawn.prototype.constructor = Pawn;
function Pawn(square, color) {
    Piece.call(this, square, color);
    this.startPosition = (color === WHITE? 2 : 7);
    this.direction = (color === WHITE? 1 : -1);

    this.type = PAWN;
}

.
.
.

/******* Knight class
 * Holds the movement of the Knight, refer to Piece for explanations.
 * @type {Piece}
 */
Knight.prototype = Object.create(Piece.prototype);
Knight.prototype.constructor = Knight;
function Knight(square, color) {
    Piece.call(this, square, color);

    this.type = KNIGHT;
} 
.
.
.
/******* King class
 * Holds the movement of the King, refer to Piece for explanations.
 * @type {Piece}
 */
King.prototype = Object.create(Piece.prototype);
King.prototype.constructor = King;
function King(square, color, has_moved) {
    Piece.call(this, square, color);

    this.type = KING;
}
.
.
.

我不确定如何正确导入所有不同的“类”以便在其他地方使用。我想从generatePiece这个文件的util.js创建module.export函数,从而把它变成一种“片段生成器”。这是一个好主意吗?

1 个答案:

答案 0 :(得分:0)

不幸的是,似乎并不是在node.js中做事的事实方式,我会试着给出一些通用的解决方案:

  

我想从util.js中生成generatePiece函数   module.export这个文件,因此把它变成了一个&#34;件   发电机&#34 ;.这是一个好主意吗?

我认为将模块用作独立的工具是一个非常简单和优雅的解决方案。它很容易单稳定,并且经常在node.js项目中使用。

  

。如果我将每个函数/对象分别添加到module.exports   对于我使用这个模块的每个对象(这几乎都是   其他对象)我需要做类似this.utils =的事情   要求(&#39; ./ utils的&#39);然后调用例如square = new   this.utils.Square(文件,等级);,看起来并不是那么好   一个解决方案。是否有更好的方式导入此文件   全局?

不是将require d库存储为对象中的属性,而是可以通过全局引用构建新的方块,这通常用于:

utils = require('./utils'); and then call, for example, square = new utils.Square(file,rank);`

甚至可以进一步细分您的模块,甚至可以创建一个零件模块或一个电路板模块。

我尝试创建尽可能多的模块。一个好处是节点中有许多库可以模拟require。如果你最终做IO,那么为你的单元测试嘲笑它是很重要的。