Anonymous user
Playing cards: Difference between revisions
→{{header|PHP}}: Added Hand implementation. Refactored Deck::deal() to allow dealing into existing CardCollection (inspired by D language implementation)
(→{{header|PHP}}: Refactored, implemented Iterator interface and a sort method for CardCollection, and various compare methods for Card) |
(→{{header|PHP}}: Added Hand implementation. Refactored Deck::deal() to allow dealing into existing CardCollection (inspired by D language implementation)) |
||
Line 2,320:
}
public function deal( $amount = 1, CardCollection $cardCollection = null )
{
if( !is_int( $amount ) || $amount < 1 )
Line 2,332:
}
$cardCollection = $cardCollection ?: new CardCollection;
foreach( $cards as $card )
{
$cardCollection->addCard( $card );
}
return $cardCollection;
}
Line 2,338 ⟶ 2,347:
{
shuffle( $this->cards );
}
}
class Hand
extends CardCollection
{
// override CardCollection __constructor
// to allow public instantiation
// but disallow instantiation with cards
public function __construct() {}
public function play( $position )
{
if( !isset( $this->cards[ $position ] ) )
{
throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
}
$result = array_splice( $this->cards, $position, 1 );
return $result[ 0 ];
}
}</lang>
Line 2,371 ⟶ 2,400:
echo PHP_EOL . count( $deck ) . ' cards in the new deck, shuffled: ' . PHP_EOL . $deck . PHP_EOL . PHP_EOL;
//
$players = array(
new Hand,
new Hand,
new Hand,
new Hand
);
// three deal rounds, with amounts: 2, 2, 3
foreach( array( 2, 2, 3 ) as $amount )
{
// deal this rounds amount to player
foreach( $players as $hand )
{
$deck->deal( $amount, $hand );
}
}
foreach( $players as $p => $hand )
{
//
$
// show player cards
echo 'Player ' . ( $p + 1 ) . ' got dealt the following ' . count( $
}
Line 2,394 ⟶ 2,440:
52 cards in the new deck, shuffled:
Player 1 got dealt the following
Player 2 got dealt the following
Player 3 got dealt the following
Player 4 got dealt the following
♥A ♥6 ♦2 ♦5 ♥J ♣T ♦3 ♠5 ♠A ♣8 ♥8 ♥7 ♥K ♦7 ♥T ♦6 ♦T ♣6 ♣3 ♣A ♦4 ♥4 ♠6 ♣9</pre>
=={{header|PicoLisp}}==
|