演習中に、while ループと if/else 句を組み合わせたので、代わりに if/else を変換して switch ステートメントを使用することにしました。
プログラムは簡単です: ゲームを停止するには、2 人のプレイヤーが 3 試合連続で勝利する必要があります。プレイヤーの値は 0 から 1 の間でランダムに並べ替えられ、ランダム性がレースに勝つ場合に備えて、ペアの一致には上限があります :)
どちらが最適なソリューションであるか、またその理由を理解したいと思います。なぜなら、スイッチ バージョンにはさらに数行のコードが必要なように思われるからです。
<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
while ($winA<=2 && $winB<=2 && $pair<=15) {
$playerA = rand(0,1);
$playerB = rand(0,1);
if ($playerA > $playerB) {
$winA ++;
$winB=0;
echo "<div>Player A Wins.</div>";
} elseif ($playerA < $playerB) {
$winB ++;
$winA=0;
echo "<div>Player B Wins.</div>";
} elseif ($playerA == $playerB) {
$pair ++;
$winA=0;
$winB=0;
echo "<div>Pair, play again!</div>";
}
}
echo "<div>There is a total of {$pair} pair matches</div>";
?>
そして今、スイッチ1...
<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
while ($winA<=2 && $winB<=2 && $pair<=15) {
$playerA = rand(0,1);
$playerB = rand(0,1);
switch ($playerA && $playerB):
//This is an error: it should have been switch(true)
case ($playerA > $playerB):
$winA++;
$winB=0;
echo "<div>Player A Wins.</div>";
break;
case ($playerA < $playerB):
$winB++;
$winA=0;
echo "<div>Player B Wins.</div>";
break;
case ($playerA == $playerB):
$pair++;
$winA=0;
$winB=0;
echo "<div>Pair, Play again!</div>";
break;
endswitch;
}
echo "<div>There is a total of {$pair} pair matches</div>";
?>