LoginSignup
37
15

More than 3 years have passed since last update.

if文なしでじゃんけん

Posted at

[PHP]じゃんけんプログラム - Qiitaを読んで、自分ならどうするか考えてみた。

解答

複雑に考えればいくらでも複雑にできるけれども、とりあえずこのくらいにした。

<?php

const WIN_LOSE_TABLE = [
    'グー' => ['チョキ' => 1, 'パー' => -1],
    'チョキ' => ['パー' => 1, 'グー' => -1],
    'パー' => ['グー' => 1, 'チョキ' => -1],
];

$printer = fn(string $my_hand, string $your_hand, int $result): string =>
    sprintf("[%s vs %s] %s", $my_hand, $your_hand,
        match ($result) {
            -1 => 'あなたの負け',
            0 => 'あいこ',
            1 => 'あなたの勝ち',
        }
    );

foreach (['グー', 'チョキ', 'パー'] as $my_hand) {
    foreach (['グー', 'チョキ', 'パー'] as $your_hand) {
        echo battle($my_hand, $your_hand, $printer), PHP_EOL;
    }
}

/**
 * 尋常に勝負
 */
function battle(string $my_hand, string $your_hand, Closure $printer): string
{
    return $printer($my_hand, $your_hand, WIN_LOSE_TABLE[$my_hand][$your_hand] ?? 0);
}

大事なのはconst WIN_LOSE_TABLEと、それを取り出すところでWIN_LOSE_TABLE[$my_hand][$your_hand] ?? 0してるところ。match ($result)のところは勝ち・負け・あいこの状態を文字列に変換してるだけ。

これだけだと見映えがしないので

絵文字を使いましょう

<?php

namespace Janken;

use Closure;

const WIN_LOSE_TABLE = [
    'グー' => ['チョキ' => 1, 'パー' => -1],
    'チョキ' => ['パー' => 1, 'グー' => -1],
    'パー' => ['グー' => 1, 'チョキ' => -1],
];

const EMOJI_TABLE = [
    'グー' => '✊',
    'チョキ' => '✌',
    'パー' => '🖐',
];

$printer = fn(string $my_hand, string $your_hand, int $result): string =>
    sprintf("[%s vs %s] %s",
        EMOJI_TABLE[$my_hand],
        EMOJI_TABLE[$your_hand],
        match ($result) {
            -1 => 'あなたの負け',
            0 => 'あいこ',
            1 => 'あなたの勝ち',
        }
    );

foreach (['グー', 'チョキ', 'パー'] as $my_hand) {
    foreach (['グー', 'チョキ', 'パー'] as $your_hand) {
        echo battle($my_hand, $your_hand, $printer), PHP_EOL;
    }
}

function battle(string $my_hand, string $your_hand, Closure $printer): string
{
    return $printer($my_hand, $your_hand, WIN_LOSE_TABLE[$my_hand][$your_hand] ?? 0);
}

動作確認: https://3v4l.org/MFqsQ

スクリーンショット 2021-02-25 1.27.28.png

やりましたね!

37
15
1

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
37
15