不要尝试在 node.js 中使用全局变量。另请注意,require
它将引用一个缓存的对象,并且实际上不会多次重新要求同一个文件。
这是一个非常通用的示例,说明如何在不使用全局变量的情况下开始设置纸牌游戏
lib/deck.js
var SUITS = ["H", "C", "D", "S"],
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var Deck = module.exports = function Deck() {
this.cards = [1, 2, 3, ..., 52];
this.shuffle();
};
Deck.prototype.shuffle = function shuffle() {
// shuffle this.cards
};
Deck.prototype.dealCard = function dealCard() {
var id = this.cards.shift();
return {id: id, rank: RANKS[id%13], suit: SUITS[id%4]};
};
lib/game.js
var Deck = require("./deck");
var Game = module.exports = function Game(numCards) {
this.numCards = numCards;
this.deck = new Deck();
};
Game.prototype.dealCards = function dealCards(player) {
for (var i=0; i<this.numCards; i++) {
player.cards.push(this.deck.dealCard());
}
};
// ...
lib/player.js
var EventEmitter = require("events").EventEmitter;
var Player = module.exports = function Player(name) {
this.name = name;
this.cards = [];
};
Player.prototype = Object.create(EventEmitter.prototype, {constructor: {value: Player}};
// ...
lib/session.js
var EventEmitter = require("events").EventEmitter,
Game = require("./game"),
Player = require("./player");
var Session = module.exports = function Session(numCards) {
EventEmitter.call(this);
this.game = new Game(numCards);
this.players = [];
this.scores = [];
};
Session.prototype = Object.create(EventEmitter.prototype, {constructor: {value: Session}});
Session.prototype.addPlayer = function addPlayer(player) {
// add the player
this.players.push(player);
// deal the player some cards
this.game.dealCards(player);
// setup event listeners
player.on("score", function(points) {
this.addScore(player, points);
});
player.on("playerTurn", function(event) {
// ...
});
};
Session.prototype.addScore = function(player, points) {
if (this.scores[player.id] === undefined) {
this.scores[player.id] = 0;
}
this.scores[player.id] += points;
};
运行.js
var Session = require("./session"),
numCards = 2;
var sessionInstance = new Session(numCards);
sessionInstance.on("addPlayer", function(player) {
this.addPlayer(player);
});
// e.g.,
// setup a net.Server and fire "addPlayer" when a user connects