Reputation: 60
I'm quite new to using OOP and wanted to create a simple cardgame. I got the following code:
class card{
private $suit;
private $rank;
public function __construct($suit, $rank){
$this->suit = $suit;
$this->rank = $rank;
}
public function test(){
echo $this->suit.' '.$this->rank;
}
}
class deck{
private $suits = array('clubs', 'diamonds', 'hearts', 'spades');
private $ranks = array(2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A');
public function create_deck(){
$cards = array();
foreach($this->suits as $suit) {
foreach ($this->ranks as $rank) {
$cards[] = new card($suit, $rank);
}
}
print_r($cards);
}
}
Say, for example that my class card had a function for dealing a card. How do I deal a king of hearts? which is already created but I don't know how to access it.
Upvotes: 0
Views: 37
Reputation: 1060
Instantiate an object like this:
$card = new card('hearts', 'K');
Upvotes: 0
Reputation: 780724
The function for dealing a card should probably be in the deck
class, not the card
class. It would be something like:
public function deal_card() {
$suit = $this->suits[array_rand($this->suits, 1)];
$rank = $this->ranks[array_rand($this->ranks, 1)];
return new card($suit, $rank);
}
Note that this has no memory of which cards were dealt. The deck
class should probably have a private $cards
property containing an array of all the cards (you can fill it in in the contructor, using a loop like in your create_deck
function). Then when you deal a card, you can remove it from this array:
public function deal_card() {
if (count($this->cards) > 0) {
$index = array_rand($this->cards, 1); // pick a random card index
$card = $this->cards[$index]; // get the card there
array_splice($this->cards, $index, 1); // Remove it from the deck
return $card;
} else {
// Deck is empty, nothing to deal
return false;
}
}
Upvotes: 1