[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];
}
普通すぎる結果になりました。