我正在尝试实现一个简单的JavaScript游戏以及该游戏的WebSocket服务器。我的问题是关于WebSocket服务器的。
我实现的代码在这里。
class Game{
constructor(){
this.GRID_SIZE = 20;
this.MAP_EDGE_RECTANGLE_COUNT = 1000;
}
init(){
this.createMap();
this.apple = [];
}
createMap(){
this.map = [];
// set map rows and columns
for(var i = 0; i < this.MAP_EDGE_RECTANGLE_COUNT; i++) {
this.map[i] = [];
for(var j = 0; j < this.MAP_EDGE_RECTANGLE_COUNT; j++){
var obj = new Object();
obj.row = i;
obj.column = j;
this.map[i][j] = obj;
}
}
// set walls
for(var i = 0; i < this.MAP_EDGE_RECTANGLE_COUNT; i++){
this.map[0][i].name = 'wall';
this.map[i][0].name = 'wall';
this.map[this.MAP_EDGE_RECTANGLE_COUNT -1][i].name = 'wall';
this.map[i][this.MAP_EDGE_RECTANGLE_COUNT -1].name = 'wall';
}
// set foods
for(var i = 0; i < 10 * this.MAP_EDGE_RECTANGLE_COUNT; i++){
var index1 = Math.floor(Math.random() * this.MAP_EDGE_RECTANGLE_COUNT);
var index2 = Math.floor(Math.random() * this.MAP_EDGE_RECTANGLE_COUNT);
this.map[index1][index2].name = 'foods';
this.map[index2][index1].name = 'foods';
}
}
}
const game = new Game();
game.init();
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log("a client connected:");
console.log("CONNECTED");
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
var counter = 0;
var interval = setInterval(function(){1
console.log('sending message to client');
ws.send('{"map:"' + game.map + '}');
}, 1000 / 10);
ws.on("close", function(ev) {
clearInterval(interval);
console.log('connection error with a client');
});
});
如您所见,代码中有一个地图对象,用于存储游戏网格的所有状态。而且我有一定的时间间隔将地图的当前状态推送给所有客户端。但是将所有地图数据发送给客户端会导致我的游戏UI出现质量问题。(发送简短数据可以解决此问题)。因此,我需要向客户发送最少的数据。
现在,这些游戏的运行机制是什么?我应该发送什么类型的数据?