我正在写一个纸牌游戏,其中有一个单一和多人模式。在单人游戏的情况下,脚本会根据玩家的动作生成动作。我的问题是,这个脚本在眨眼之间移动,我希望玩家感觉AI正在“思考”它的移动,因此在显示它的2秒之前,每个响应都要等待。
由于我使用的是带有javascript客户端的browser +服务器架构,所以这种等待是相当困难的。我目前拥有的代码并没有按照我所希望的那样运行。其思想是,当响应从websocket客户端到达并由ai生成时,响应将被推入队列。有一个间隔,每2秒运行一次,试图弹出队列。这是我的代码:
// interval
var responseQueue = [];
$interval(function () {
var response = responseQueue.shift();
if (response !== undefined) {
processResponse(response);
}
}, OPPONENT_MOVE_REFRESH_INTERVAL);
// websocket response
SocketFactory.subscribe("/user/queue/game.gameResponse", function (response) {
var res = JSON.parse(response.body);
// the current player moved, refreshing view
if ($scope.username === res.currentPlayerId) {
processResponse(res);
} else {
// the opponent moved (the ai in this case)
responseQueue.push(res);
}
});我得到的似乎是一种随机行为。卡片出现,但不是在2秒间隔和数据有时丢失。我做错了什么?
注意到,是可能的球员移动不止一次,所以有时我得到2-3AI快速连续移动。
发布于 2015-02-08 03:51:12
下面这样的内容应该更好地工作,因为它确保了响应和屏幕上操作之间的延迟,而不仅仅是基于上次预定的视图更新的延迟。我仍然不确定这是否会阻止您丢失的卡(实际上您的代码看起来还好),但它将使延迟更加一致。
// interval
var responseQueue = [];
function next() {
var response = responseQueue.shift();
if (response !== undefined) {
processResponse(response);
}
if(responseQueue.length) next.timer=setTimeout(next, 2000);
}
// websocket response
SocketFactory.subscribe("/user/queue/game.gameResponse", function (response) {
var res = JSON.parse(response.body);
// the current player moved, refreshing view
if ($scope.username === res.currentPlayerId) {
processResponse(res);
} else {
// the opponent moved (the ai in this case)
clearTimeout(next.timer);
responseQueue.push(res);
next.timer=setTimeout(next, 2000);
}
});现在,什么都不会发生,直到2秒后,其他事情。
https://stackoverflow.com/questions/28390118
复制相似问题