使用 mt_rand() 產生高品質隨機數:
function roll($sides = 6) {
return mt_rand(1, $sides);
}
echo roll(6); // 六面骰
echo roll(20); // 二十面骰
準備名字、姓氏陣列,使用 array_rand() 或 shuffle() 組合:
$male = ['William', 'Henry', 'John', 'Pat'];
$last = ['Smith', 'Jones', 'Winkler', 'Cooper'];
echo $male[array_rand($male)] . ' ' . $last[array_rand($last)];
// 批量產生
shuffle($male); shuffle($last);
for ($i=0; $i<4; $i++) echo $male[$i].' '.$last[$i].'<br>';
進階:從文字檔讀取名單 $male = explode("\n", file_get_contents('names.male.txt'));
將「場景、目標、敵人、複雜度」分別存入文字檔,隨機組合生成 RPG 場景:
$settings = explode("\n", file_get_contents('scenario.settings.txt'));
$objectives = explode("\n", file_get_contents('scenario.objectives.txt'));
$antagonists = explode("\n", file_get_contents('scenario.antagonists.txt'));
$complications = explode("\n", file_get_contents('scenario.complications.txt'));
shuffle($settings); shuffle($objectives); shuffle($antagonists); shuffle($complications);
echo $settings[0].' '.$objectives[0].' '.$antagonists[0].' '.$complications[0].'<br>';
$suits = ['Spades','Hearts','Clubs','Diamonds'];
$faces = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace'];
$deck = [];
foreach ($suits as $suit) foreach ($faces as $face) $deck[] = ['face'=>$face, 'suit'=>$suit];
shuffle($deck);
$card = array_shift($deck);
echo $card['face'].' of '.$card['suit'];
發牌後計算抽到特定牌面/花色的機率:
$hands = [1=>[], 2=>[]];
for ($i=0; $i<5; $i++) {
$hands[1][] = implode(' of ', array_shift($deck));
$hands[2][] = implode(' of ', array_shift($deck));
}
function calculate_odds($draw, $deck) {
$remaining = count($deck); $odds = 0;
foreach ($deck as $card) {
if (($draw['face']==$card['face'] && $draw['suit']==$card['suit']) ||
($draw['face']=='' && $draw['suit']==$card['suit']) ||
($draw['face']==$card['face'] && $draw['suit']=='')) $odds++;
}
return "$odds in $remaining";
}
$draw = ['face'=>'Ace', 'suit'=>'Spades'];
echo calculate_odds($draw, $deck); // 輸出如 "1 in 42"
$draw = ['face'=>'', 'suit'=>'Hearts'];
echo calculate_odds($draw, $deck); // 輸出剩餘紅心數量
本系列將持續分享更多遊戲開發實用片段,敬請期待後續篇章。