创建一个函数has_twenty_ones,如果游戏中至少有一个玩家有21,则返回true,否则返回false。此函数应使用twenty_ones函数。
function has_twenty_ones($game){
function twenty_ones($game)
{
$players_with_score_21 = [];
foreach ($game['players'] as $name => $player) {
$distance = 21 - $player['score'];
if ($distance < 0) {
continue;
}
if ($distance == 21) {
$players_with_score_21 = [$name];
}
}
return $players_with_score_21;
}
return isset($players_with_score_21);
}
编码的最佳方法是什么
答案 0 :(得分:2)
检查twenty_ones
函数的返回是否为空,如果返回false,则返回false {0}返回twenty_ones
。
function has_twenty_ones($game){
function twenty_ones($game){
$players_with_score_21 = [];
foreach ($game['players'] as $name => $player) {
$distance = 21 - $player['score'];
if ($distance < 0) {
continue;
}
if ($distance == 21) {
$players_with_score_21 = [$name];
}
}
return $players_with_score_21;
}
$playersWithScore = twenty_ones($game);
if (!empty($playersWithScore)) {
return $playersWithScore;
} else {
return false;
}
}
答案 1 :(得分:0)
我不确定为什么你需要两个功能。
正如@RiggsFolly所提到的,你实际上并没有调用twenty_ones()函数。为什么不拥有以下代码:
function has_twenty_ones($game)
{
foreach($game['players'] as $name => $player)
{
$distance = 21 - $player['score'];
if ($distance < 0) {
continue;
}
// If at least one player has 21, return true.
if($distance == 21) {
return true;
}
}
return false;
}
当遇到得分为21的玩家时,上述内容将返回true,否则将返回false。
答案 2 :(得分:-1)
function twenty_ones($game)
{
$players_with_score_21 = [];
foreach ($game['players'] as $name => $player) {
$distance = 21 - $player['score'];
if ($distance < 0) {
continue;
}
if ($distance == 21) {
$players_with_score_21 = [$name];
}
}
return $players_with_score_21;
}
function has_twenty_ones($game){
if (count ($this->twenty_ones($game)) > 0 )
return true;
else
return false;
}