Last active
November 30, 2022 10:39
-
-
Save katsube/de9669333164b112f64b30e0572b2f4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* ジョーカーが何枚目に排出されるか数える | |
* | |
*/ | |
//---------------------------------------- | |
// ライブラリ | |
//---------------------------------------- | |
require_once('trump.class.php'); | |
//---------------------------------------- | |
// メイン処理 | |
//---------------------------------------- | |
// 山札を作成 | |
$cards = new Trump(); | |
// ジョーカーが見つかるまで山札を引き続ける | |
$count = 1; | |
while( $cards->draw() !== false ) { | |
if( $cards->isJoker() ) { | |
printf("%s枚目にジョーカーが排出されました\n", $count); | |
break; | |
} | |
$count++; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* トランプ管理クラス - trump.class.php | |
* | |
* @author M.Katsube | |
* @version 1.0.0 | |
*/ | |
class Trump{ | |
//--------------------------- | |
// クラス定数 | |
//--------------------------- | |
const SUIT = ['♣', '♦', '♥', '♠']; | |
const RANK = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']; | |
const JOKER = 'ジョーカー'; | |
//--------------------------- | |
// プロパティ | |
//--------------------------- | |
private $cards; // 山札 | |
private $lastCard; // 最後に引いたカード | |
/** | |
* コンストラクタ | |
*/ | |
function __construct(){ | |
$this->_initCards(); // 山札用の配列を初期化 | |
} | |
/** | |
* 山札からカードを1枚引く | |
*/ | |
function draw(){ | |
// 山札にカードが残っているかチェック | |
if( $this->getCardsCount() === 0 ){ | |
return(false); | |
} | |
// 山札の先頭からカードを1枚引く | |
$card = array_shift($this->cards); // 山札から1枚削除される | |
// https://www.php.net/manual/ja/function.array-shift | |
$this->lastCard = $card; // 最新カードをオブジェクト内に保持 | |
return($card); | |
} | |
/** | |
* 最後に引いたカードがジョーカーか判定する | |
*/ | |
// ★ここにコードを追加する その1★ | |
/** | |
* 山札の残り枚数を取得する | |
*/ | |
// ★ここにコードを追加する その2★ | |
/** | |
* トランプ用配列を初期化する | |
*/ | |
private function _initCards(){ | |
$cards = [ ]; | |
for($i=0; $i<count(self::SUIT); $i++){ // 絵柄の数だけループ | |
for($j=0; $j<count(self::RANK); $j++){ // 数字の数だけループ | |
// カードを山札に追加する | |
$cards[ ] = [ | |
'suit' => self::SUIT[$i], | |
'number' => self::RANK[$j] | |
]; | |
} | |
} | |
// ジョーカーを最後に追加する | |
$cards[ ] = self::JOKER; | |
// 山札をシャッフルする | |
shuffle($cards); // 引数の値を直接書き換えます | |
// https://www.php.net/manual/ja/function.shuffle.php | |
$this->cards = $cards; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment