这样的逻辑可能在php中

时间:2013-01-25 10:38:29

标签: php html

  

可能重复:
  How can one describe a rock-paper-scissors relationship between 3 items?

大家好我正在为一个石头剪刀游戏做一个PHP任务,我试图做规则检查部分,并希望使用下面的红宝石功能的逻辑,我试图尽可能避免条件。

任何人都有任何想法?

def who_wins(p1, p2)
  win_moves = {"rock" => "paper", "paper" => "scissors", "scissors" => "rock"}
  ([p1, p2] & win_moves.values_at(p1, p2)).first
end

who_wins("rock", "paper") # "paper"
who_wins("scissors", "rock") # "rock"
who_wins("scissors", "scissors") # nil

3 个答案:

答案 0 :(得分:1)

我做的快速功能:

function who_wins($p1, $p2){
    $win_moves = array("rock" => "paper", "paper" => "scissors", "scissors" => "rock");
    if($p1 === $p2){
        return null;
    }
    return ($win_moves[$p1] === $p2) ? $p2 : $p1;
}

答案 1 :(得分:0)

尝试这样的事情。唯一的条件是$ p1和$ p2是相同的。逻辑由数组函数处理。

function who_wins($p1, $p2) {
    if ($p1 === $p2) {
        return "nil";
    }
    $actions = array("rock", "scissors", "paper");

    $selected_actions = array_merge(array_keys($actions, $p1), array_keys($actions, $p2));
    sort($selected_actions);

   return $actions[$selected_actions[0]];
}

答案 2 :(得分:0)

不确定您的原始功能究竟是什么,但这是一个非常紧凑的解决方案 我确信有一些更爱你可以摆脱if声明。

<?php
echo who_wins("rock", "paper")."\n";
echo who_wins("scissors", "rock")."\n";
echo who_wins("scissors", "scissors")."\n";

function who_wins($p1,$p2) {
    $comb = array (
    "rock"  => 0,
    "paper" => 1,
    "scissors"  => 2,
    );

    $result = (3+$comb[$p1]-$comb[$p2]) % 3;

    if ($result==1){ return $p1; } elseif($result==2) { return $p2; } 

}
?>