javascript-如何在不复制代码的情况下删除耦合?
作者:互联网
我正在为多人游戏制作服务器,但在弄清楚如何使逻辑模块化方面遇到一些问题.当玩家移动时,我想更新对象,更新数据库记录,并将移动发送给所有连接的客户端.现在,我正在这样做:
var socket = require('./socket');
var db = require('./db');
function Player(id, x, y) {
this.id = id;
this.x = x;
this.y = y;
}
Player.prototype.move = function(x, y) {
this.x = x;
this.y = y;
db.update({id: this.id}, {x: x, y: y});
socket.emit('player moved', {x: x, y: y});
}
这将套接字和数据库紧密耦合到感觉错误的播放器对象.但是,我不想每次更新播放器对象时都在游戏循环中执行db.update和socket.emit.
正确的做法是什么?
解决方法:
我会做两件事:
1)让您的Player类发出事件.这样一来,您将来便可以添加更多触发器,而无需修改Player类
2)使用pos对象保存x和y值.这使代码更加简洁.
// In Player file
var EventEmitter = require('events').EventEmitter;
function Player(id, pos) {
this.id = id;
this.pos = pos;
}
Player.events = new EventEmitter();
Player.prototype.move = function (pos) {
Player.events.emit('move', this);
};
module.exports = Player;
// In database file...
var db = require('./db');
var Player = require('./Player');
Player.events.on('move', function (player) {
db.update({id: player.id}, player.pos);
});
// In socket file...
var socket = require('./socket');
var Player = require('./Player');
Player.events.on('move', function (player) {
socket.emit('player moved', player.pos);
});
标签:node-js,game-engine,javascript 来源: https://codeday.me/bug/20191120/2042977.html