19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[JavaScript] コナミコマンドのスニペット

Last updated at Posted at 2014-06-23

Twitterで流行っているようなのでコナミコマンドを実装してみた。


(function(cmd, fire) {
  var keys = [];
  var l = cmd.length, CMD = cmd.join(',');
  $(document).on('keydown', function(event) {
    keys.push(event.which);
    if (keys.length < l) return true;
    if (keys.join(',') === CMD) fire();
    keys = [];
  });
})([38,38,40,40,37,39,37,39,66,65], function(){
  // ここにコナミコマンドのイベントを実装
});

第一引数のcmdを置き換えれば他のコマンドにも応用可能。

# 関数化、リトライ対応版
# ほぼTwitterのソースだけど
class CommandWatcher
  constructor: (commands) ->
    @keys = []
    @length = commands.length
    @command = commands.join ','
  watch: (handler) =>
    watcher = @
    $(document).on 'keydown', (event) ->
      watcher.keys.push event.which
      # マッチしたら実行後、即return
      if watcher.keys.length is watcher.length and watcher.keys.join(',') is watcher.command
        handler()
        watcher.keys = []
        return
      # マッチしなかったらリセット
      if watcher.command.indexOf(watcher.keys.join(',')) isnt 0
        watcher.keys = []
        return

new CommandWatcher([38,38,40,40,37,39,37,39,66,65]).watch ->
  # ここにコナミコマンドのイベントを実装
19
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?