なつかしの裏技 prototype.jsの練習

お知らせ:「コナミコマンド」を実装しました

http://n-styles.com/main/archives/2007/07/26-033445.php

すごい面白いアイデアです。

prototype.jsも忘れかけてるので、prototype.jsでSecretCommandクラスを作ってみました。

var SecretCommand = Class.create();
SecretCommand.prototype = {
execute_times: 0,
state: 0,
key_codes: [],
command_functions: [Prototype.K],
initialize: function(key_codes, command_functions) {
this.key_codes = key_codes;
this.command_functions = command_functions;
var body = document.getElementsByTagName('body')[0];
Event.observe(body, "keydown", this.keypress.bindAsEventListener(this));
},
keypress: function(event) {
if (this.key_codes[this.state] == event.keyCode) {
if (this.key_codes.length == ++this.state) {
this.success();
this.state = 0;
}
} else {
this.state = 0;
}
},
success: function() {
this.execute_times = ++this.execute_times % this.command_functions.length;
this.command_functions[this.execute_times - 1]();
}
};

ほとんど同じように動かすには、以下みたいにすればいいです。

Event.observe(window, "load", init);
function init() {
new SecretCommand(
[38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
[
function() {alert("パワーアップ!"); document.bgColor = "#FFEEEE";},
function() {alert("しつこいよ?");},
function() {alert("しつこいって!");},
function() {alert("さようなら"); window.close();},
]
);
}

各ブラウザでの動作確認は全然してません;;

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.