【问题标题】:How to detect konami code with Rx.js (reactive extensions for javascript)?如何使用 Rx.js(javascript 的响应式扩展)检测 konami 代码?
【发布时间】:2010-12-02 15:31:33
【问题描述】:

我想开始学习Rx.js,我正在寻找一个很酷的例子来开始学习。如何使用 Rx.js 检测 konami code

我想检测一系列按键事件(上下左右 B A)并在发生这种情况时显示图像。

【问题讨论】:

    标签: reactive-extensions-js


    【解决方案1】:

    这是我的版本:

    <html>
    <head>
    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="rx.js"></script>
    <script type="text/javascript" src="rx.jQuery.js"></script>
    </head>
    <body>
    <p id="result"></p>
    <script type="text/javascript">
        $(function() {
            var konami = $(document).toObservable("keyup").Select(function(e) {
                return e.keyCode
            }).SkipWhile(function(k) {
                return (k != 38)
            }).BufferWithCount(
                10
            ).Where(function(ks) {
                return ks.length == 10 &&
                    ks[0] == 38 && ks[1] == 38 &&
                    ks[2] == 40 && ks[3] == 40 &&
                    ks[4] == 37 && ks[5] == 39 &&
                    ks[6] == 37 && ks[7] == 39 &&
                    ks[8] == 66 && ks[9] == 65
            })
    
            var konamisub = konami.Subscribe(function(e) {
                $("#result").text("KONAMI!")
                $("#result").fadeIn().fadeOut()
            })
        })
    </script>
    </body>
    </html>
    

    我使用Select 将按键事件流转换为按键代码流,然后忽略按键直到用户使用SkipWhile 按下(按键代码38),然后使用BufferWithCount 收集10 个按键,然后使用Where 检查击键。

    我尝试使用 BufferWithTime,但它往往会在击键中间中断。

    如果有人可以提出改进建议,我很乐意听取他们的意见。

    【讨论】:

    【解决方案2】:

    由于您正在学习,我不想破坏您的答案,但我会尝试将问题视为“如何将 Key up 事件转换为 序列 最近按下的最后 10 个字符”,并将该列表与“UUDDLRLRBA”的常量列表进行比较。 (提示:Buffer、Where、Select、Take、Repeat 都是你的朋友)

    【讨论】:

    • 其实我不介意剧透 :) 但它不会那么有趣。感谢您的提示!
    • 我得到了它的工作,但它不使用TakeRepeat。在这种情况下,您将如何使用 Take 和 Repeat?
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2014-09-25
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多