javascriptで、if文を1つも使わないジャンケンの勝敗判定を作ってみた。
出した手であるグー、チョキ、パーがそれぞれオブジェクトとして存在し、それぞれのオブジェクトは相手の手による勝敗を知っている。
処理としては以下のようなイメージで行われる。
1.「メイン処理」は「コンピュータの出した手」に「あなたの手」の勝敗を求めるように言う。
2.「コンピュータの出した手」は勝敗を求めるために、「あなたの手」に「私の手はXXだけど、あんたはその手に勝ってる?」と聞く。
3.「あなたの手」は「コンピュータの出した手」から聞いた手に対する勝敗を答える。
// メイン処理
function janken() {
var teList = [ new Guu(), new Choki(), new Paa() ];
var youTe = teList[ prompt("0:グー、1:チョキ、2:パー", "") ];
var comTe = teList[ Math.floor(Math.random() * 3) ];
var result = comTe.judgment(youTe) // comTe が youTe の勝敗を判定
alert("あなた:" + youTe.text + " 相手:" + comTe.text + " → 勝敗:" + result);
}
// グー、チョキ、パー クラス
// 普通のオブジェクト指向言語の場合、同じ親クラスから継承して作る
function Guu() {
this.text = "グー";
this.judgment = function (te) { return te.judgVsG(); };
this.judgVsG = function () { return "あいこ"; };
this.judgVsC = function () { return "勝ち"; };
this.judgVsP = function () { return "負け"; };
}
function Choki() {
this.text = "チョキ";
this.judgment = function (te) { return te.judgVsC(); };
this.judgVsG = function () { return "負け"; };
this.judgVsC = function () { return "あいこ"; };
this.judgVsP = function () { return "勝ち" ; };
}
function Paa() {
this.text = "パー";
this.judgment = function (te) { return te.judgVsP(); };
this.judgVsG = function () { return "勝ち"; };
this.judgVsC = function () { return "負け"; };
this.judgVsP = function () { return "あいこ"; };
}