首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用javascript中的间隔顺序处理websocket响应?

如何使用javascript中的间隔顺序处理websocket响应?
EN

Stack Overflow用户
提问于 2015-02-08 03:00:18
回答 1查看 402关注 0票数 0

我正在写一个纸牌游戏,其中有一个单一和多人模式。在单人游戏的情况下,脚本会根据玩家的动作生成动作。我的问题是,这个脚本在眨眼之间移动,我希望玩家感觉AI正在“思考”它的移动,因此在显示它的2秒之前,每个响应都要等待。

由于我使用的是带有javascript客户端的browser +服务器架构,所以这种等待是相当困难的。我目前拥有的代码并没有按照我所希望的那样运行。其思想是,当响应从websocket客户端到达并由ai生成时,响应将被推入队列。有一个间隔,每2秒运行一次,试图弹出队列。这是我的代码:

代码语言:javascript
复制
        // 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快速连续移动。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-08 03:51:12

下面这样的内容应该更好地工作,因为它确保了响应和屏幕上操作之间的延迟,而不仅仅是基于上次预定的视图更新的延迟。我仍然不确定这是否会阻止您丢失的卡(实际上您的代码看起来还好),但它将使延迟更加一致。

代码语言:javascript
复制
 // 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秒后,其他事情。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28390118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档