Javascript 使用node.js更正模块组织

Javascript 使用node.js更正模块组织,javascript,node.js,module,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

我已经用纯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>

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

不幸的是,node.js中似乎没有一种实际的操作方法,我将尝试给出几个通用的解决方案:

我想让util.js中的generatePiece函数 module.export,从而将其转换为某种“片段” 发电机”。这是个好主意吗

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

。如果我将每个函数/对象单独添加到module.exports,则 对于使用此模块的每个对象(几乎是任何 其他对象)我需要这样做。utils= 要求('./utils');然后调用,例如,square=new this.utils.Square(文件,秩);,看起来不太好 一个解决方案的设计。有没有更好的方法导入这个文件 全球

不需要将
require
d库作为属性存储在对象中,您只需通过全局引用构造新的正方形,这是常用的:

utils=require('./utils');然后调用,例如,
square=new-utils.square(file,rank)`

甚至可以进一步细分模块,甚至可以创建一个单块模块或单板模块

我尝试创建尽可能多的模块。一个好处是节点中有很多库可以模拟
require
s。如果您最终完成了IO,那么在单元测试中模拟它可能很重要

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 : [];
}
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;
}
.
.
.