LoginSignup
3
0

More than 3 years have passed since last update.

計算でじゃんけん

Last updated at Posted at 2021-02-25

[PHP]じゃんけんプログラムと、if文なしでじゃんけんを読んで自分でもやってみた。

まずは、じゃんけんの勝敗を表にする。
9パターンしかないので、そこに数値を入れると下のようになります。

グー(0) パー(1) チョキ(2)
グー(0) あいこ(0) 負け(2) 勝ち(1)
パー(1) 勝ち(1) あいこ(0) 負け(2)
チョキ(2) 負け(2) 勝ち(1) あいこ(0)

縦軸を$player_hand、横軸を$pc_handとすると、計算方法は下の通りです。

$result = ($player_hand - $pc_hand + 3) % 3;

これを邪悪な三項演算子に放り込む。
配列だけ済むので修正しました。

$judgment = $result == 0 ? "あいこ" : ($result == 1 ? "勝ち" : "負け");

特に目新しい物がないけど、こんな感じになる。

<?php

const RPS = ["グー", "パー", "チョキ"];
const JUDGMENT = ["あいこ", "勝ち", "負け"];

foreach (RPS as $player_hand) {
    foreach (RPS as $pc_hand) {
        $judgment = janken($player_hand, $pc_hand);
        echo $player_hand, ":", $pc_hand, ":", $judgment, PHP_EOL;
    }
}

function janken(string $player_hand, string $pc_hand): string {
    $result = (array_search($player_hand, RPS) - array_search($pc_hand, RPS) + 3) % 3;
    return JUDGMENT[$result];
}

普通すぎる結果になりました。

image.png

3
0
7

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
3
0