我有一个游戏
game = {
turn: 5,
players : []
}
game.events = new events.emitter()
game.events.on('attack', handleAttack)
我需要将游戏状态精确地克隆(深入)到另一个对象,以便我可以为 AI 运行游戏模拟。我将如何克隆事件对象?
最佳答案
正如评论中所指出的,不要在函数中包含状态,这样就没有必要复制函数。
这是一个相当简单的例子。
const EventEmitter = require('events');
class Game {
constructor(name, turn) {
this.turn = turn;
this.name = name;
this.events = new EventEmitter();
this.events.on('attack', () => {
console.log(`${this.name} is attacking`);
})
}
clone(){
const copy = new Game(this.name, this.turn);
//clone the other properties
return copy;
}
}
const g1 = new Game("One", 5);
const g2 = new Game("Two", 4);
g1.events.emit('attack');
g2.events.emit('attack');
const g3 = g1.clone();
g3.events.emit('attack');
您必须特别注意克隆属性本身,但请注意 g3 只是 g1 的副本。希望这会有所帮助。
关于javascript - node.js 克隆 eventemitter 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294481/