這幾天逛Blog發現到一篇文章,是由Kai所寫的[PHP]隨機撲克牌,內容提到一個題目,一時技癢也寫了一段程式碼,答案和Kai所寫的一樣,不過採用了大量的陣列函式,大家互相交流吧!

//建立牌組
$skin = array('Spade','Heart','Diamond','Club');
foreach($skin as $key => $icon){
    for($i=1;$i<=13;$i++){
        $cards[$key.$i] = "{$icon} {$i}";
    }
}

//洗牌
srand(time());
shuffle($cards);

//各發5張牌
$palyer = array('A','B');
foreach($palyer as $index => $name){
    for($i=0;$i<5;$i++){
        $player[$name][] = array_pop($cards);   
    }
    //整理牌組
    arsort($player[$name]);
}

//結果
print_r($player);

/*
Array
(
    [A] => Array
        (
            [1] => Heart 8
            [3] => Heart 7
            [0] => Diamond 11
            [2] => Club 12
            [4] => Club 10
        )

    [B] => Array
        (
            [3] => Spade 2
            [0] => Spade 1
            [1] => Heart 2
            [2] => Heart 12
            [4] => Diamond 6
        )

)
*/
之前沒有考慮到要依照花色規則進行排序,後來在PTT的PHP板看到有鄉民提到,所以改寫了一下程式碼。透過花色的單字英文字首取得的ord()值剛好符合「黑桃>紅心>方塊>梅花」的規則,排除黑桃1的特例後,為牌組每張牌建立排序用的權重值,並在每位玩家取得手牌之後 利用array_multisort()重新排序。
$skins = array("spade","heart","diamond","club");
$icons = array(
	"spade"   => "♠",
	"heart"   => "♥",
	"diamond" => "♦",
	"club"    => "♣"
);
//建立牌組
foreach($skins as $key => $skin){
    for($no=1;$no<=13;$no++){
		//計算各牌色權重值
		if("spade" == $skin && 1 == $no) {
			$weight = ord($skin) + 14;
		} else {
			$weight = ord($skin) + $no;			
		}
		//新牌張
		$cards[$weight] = array(
			//權重值
			"weight" => $weight,
			//花色名稱
			"skin"   => $skin,
			//花色圖示
			"icon"   => $icons[$skin],
			//牌號
			"no"     => $no
		);
    }
}

//洗牌
srand(time());
shuffle($cards);

//各發5張牌
$palyers = array("Tom", "Jack", "Bill");
$num = 5;
foreach($palyers as $key => $name){
	$flag = array();
    for($i=0;$i<$num;$i++){
		//從牌組抽一張
		$card = array_pop($cards);
		//記錄權重排序參考
		$flag[] = $card["weight"];
		//分派給玩家
        $player[$name][] = $card;
    }
	//整理牌組(依照權重值)
	array_multisort($flag, SORT_DESC, $player[$name]);
}

低溫烘培 發表在 痞客邦 PIXNET 留言(0) 人氣()