LoginSignup
63
49

More than 3 years have passed since last update.

じゃんけんアルゴリズムをちょっと応用

Last updated at Posted at 2013-10-27

じゃんけんの勝敗判定

グー・チョキ・パーの3種類で判定

じゃんけん勝敗判定アルゴリズムの思い出

こちらの記事を参考にさせていただきました。

グー = 0
チョキ = 1
パー = 2

として、

(自分の手 - 相手の手 + 3) % 3

の値を見て

0 = 引き分け
1 = 負け
2 = 勝ち

というものです。
数学に強い人なら何も説明しなくても「あーなるほど」と分かると思います。

自分が勝つとき

自分 相手 差 + 3 (差 + 3) % 3
0 1 -1 2 2
1 2 -1 2 2
2 0 2 5 2

自分が負けるとき

自分 相手 差 + 3 (差 + 3) % 3
0 2 -2 1 1
1 0 1 4 1
2 1 1 4 1

引き分けのとき

自分 相手 差 + 3 (差 + 3) % 3
0 0 0 3 0
1 1 0 3 0
2 2 0 3 0

グー・チョキ・パー・皇帝・奴隷の5種類で判定

皇帝

  • 基本勝つ
  • 但し 奴隷 だけには負ける

奴隷

  • 基本負ける
  • 但し 皇帝 だけには勝てる

というルールを採用したとき。
(手をどんな形にするのか知らないが)

グー = 0
チョキ = 1
パー = 2
奴隷 = 3
皇帝 = 6

1. 自分か相手に皇帝・奴隷が含まれているかチェック。

含まれていなければ通常通り処理をして結果を返す。

2. それぞれの手を 3で割って小数点以下を切り捨てる

$you = (int)($you / 3);
$com = (int)($com / 3);

3. 通常通り判定する

通常時

記号
グー 0
チョキ 1
パー 2

3で割ったとき

記号
グー・チョキ・パー 0
奴隷 1
皇帝 2

通常時の処理をそのまま適用しても正しく判定出来ることが分かります。

PHPでの実装例

<?php

// 勝敗判定関数
function battle($a, $b) {
    if ($a > 2 || $b > 2) {
        $a = (int)($a / 3);
        $b = (int)($b / 3);
    }
    return ($a - $b + 3) % 3;
}

// 手のリスト
$hand_list = array(
    0 => 'グー',
    1 => 'チョキ',
    2 => 'パー',
    3 => '奴隷',
    6 => '皇帝',
);

// 結果リスト
$result_list = array(
    2 => 'あなたの勝ちです',
    1 => 'あなたの負けです',
    0 => 'あいこです',
    -1 => '不明',
);

// 手が送信されたとき勝負を実行
if (isset($_POST['you'])) {
    // 整数型にキャスト(不正な値をエラー無しに防ぐ効果もある)
    $you = (int)$_POST['you'];
    // コンピュータの手を選出
    $com = array_rand($hand_list);
    if (!isset($hand_list[$you])) {
        // 不正な値のときは自分の手を「?」、結果を「不明」にする
        $hand_list[$you = $result = -1] = '?';
    } else {
        // 正しい値のときは関数に渡す
        $result = battle($you, $com);
    }
}

// ヘッダー送信
header('Content-Type: application/xhtml+xml; charset=utf-8');

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja">
  <head>
    <title>じゃんけんゲーム</title>
    <style type="text/css">
      label { display: block; }
    </style>
  </head>
  <body>
    <h1>じゃんけん</h1>
    <form action="" method="post">
      <label><input type="radio" name="you" value="0" checked="checked" />グー</label>
      <label><input type="radio" name="you" value="1" />チョキ</label>
      <label><input type="radio" name="you" value="2" />パー</label>
      <label><input type="radio" name="you" value="6" />皇帝</label>
      <label><input type="radio" name="you" value="3" />奴隷</label>
      <label><input type="submit" value="勝負!" /></label>
    </form>
<?php if (isset($result)): ?>
    <h1>勝負!</h1>
    <p>
      あなた: <?=$hand_list[$you]?><br />
      コンピュータ: <?=$hand_list[$com]?><br />
      <?=$result_list[$result]."\n"?>
    </p>
<?php endif; ?>
  </body>
</html>
63
49
0

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
63
49