gpt4 book ai didi

javascript - 如何在不复制代码的情况下去除耦合?

转载 作者:搜寻专家 更新时间:2023-10-31 23:47:55 25 4
gpt4 key购买 nike

<分区>

我正在为多人游戏制作服务器,但在弄清楚如何使逻辑模块化时遇到了一些问题。当玩家移动时,我想更新对象,更新数据库记录并将移动发送到所有连接的客户端。现在我是这样做的:

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。

这样做的正确方法是什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com