首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

25 個實用 PHP 遊戲程式碼片段分享 (第一部分)

     編輯:PHP 相關知識

簡單擲骰器

使用 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); // 輸出剩餘紅心數量

本系列將持續分享更多遊戲開發實用片段,敬請期待後續篇章。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved