0

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.

1
  • 1
    $card = new card('hearts', 'K'); will deal the king of hearts and assign it to the $card variable. Commented Dec 12, 2015 at 0:35

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Instantiate an object like this:

$card = new card('hearts', 'K');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.