My First JavaScript – Konami Code
Posted on May 24th, 2009 at 15:50 by fr3@K

上週在我的 feed reader 上看到了個好玩的東西 - Konami Code.

原文作者引用了 jQuery 主站上的一段 JavaScript, 也明白的說了這個 script 的一個缺陷 - 隨著愈多的 keypress, 它會愈跑愈慢:

It’s a bit sloppy, though: the kkeys array will increase in size with every keypress, which means the page will get slower and slower as you press keys.

把 coding style 調整成自己比較習慣的風格, 加上幾行處理過多 user key log 的 code 以修正原文作者所說的問題, 補上了注解. Here it is, 我的第一個 JavaScript 程式:

    JavaScript:
    1. if(window.addEventListener)
    2. {
    3.   var target = "http://fsfoundry.org/codefreak/2009/05/24/my-first-javascript-konami-code/";
    4.   var konami_code = "38,38,40,40,37,39,37,39,66,65";
    5.   var user_key_log = [];
    6.   var max_keys_to_log = 10;
    7.  
    8.   window.addEventListener(
    9.     "keydown",
    10.     function(ev)
    11.     {
    12.       user_key_log.push(ev.keyCode); // push_back
    13.       var user_keys = user_key_log.toString();
    14.  
    15.       // Searches for konami_code in user_keys.
    16.       if(user_keys.indexOf(konami_code)>= 0)
    17.         window.location = target;
    18.  
    19.       // Cleans up user_key_log, if its length out
    20.       // numbered max_keys_to_log.
    21.       while(user_key_log.length> max_keys_to_log)
    22.         user_key_log.shift(); // pop_front
    23.     },
    24.     true);
    25. }

只要你沒把 browser 的 JavaScript 關掉, 在 COdE fr3@K 的任何一頁輸入 上上下下左右左右BA, 就會把你帶回到這篇文字.

Tested to work with:

  • Firefox 3.0.10
  • Opera 9.64
  • Epiphany Web Browser 2.24.1

Note: I don't know why, but as the original script from jQuery, my version doesn't work with IE 6 on my XP box at office.


Something interesting that I can't help wondering, 連我這個從沒認真看過 JavaScript 更別說寫過的人都能在知道問題後稍微 google 一下把這問題修掉, 難道 jQuery 網站的作者是覺得這段 code 純屬搞笑而隨便寫寫嗎?

del.icio.us:My First JavaScript - Konami Code digg:My First JavaScript - Konami Code spurl:My First JavaScript - Konami Code newsvine:My First JavaScript - Konami Code furl:My First JavaScript - Konami Code Y!:My First JavaScript - Konami Code 黑米共享書籤:My First JavaScript - Konami Code 推推王:My First JavaScript - Konami Code
Previous Post
« I Like to Move It «
Next Post
» Observer Pattern, Done Differently »

2 Comments »

Comment #6614

因為 IE 要用 window.attachEvent 而不是 addEventListener :p

Comment by ericsk — May 24, 2009 @ 17:29


Comment #6618

Thanks ericsk, I will give it a try.

Comment by fr3@K — May 24, 2009 @ 20:56


Comments RSS TrackBack URI

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>