card game - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of card game.php

  1. <?php
  2.  
  3. // Optionally only choose specific types of cards
  4. $card_types = array(1,2,5);  // $card_types = array();
  5.  
  6. // Maximum cards in the deck
  7. $deckSize = 100;
  8.  
  9. // Number of hands
  10. $hands = 2;
  11.  
  12. // Number of cards in each hand
  13. $cardsInHand = 10;
  14.  
  15. $cardTypes = array(
  16.   array('qty' => 50, 'img' => 'https://img.scryfall.com/cards/large/front/9/3/9362f606-fafc-46b9-bf30-87b0799d885a.jpg'),  
  17.   array('qty' => 25, 'img' => 'https://img.scryfall.com/cards/large/front/1/9/19c2ce16-840b-4971-b4cc-89c8cdc5b093.jpg'),
  18.   array('qty' => 25, 'img' => 'https://img.scryfall.com/cards/large/front/b/5/b5115083-0365-4a87-86be-c6d771a116e7.jpg')
  19. );
  20.  
  21. // Build the entire deck
  22. $deck = array();
  23. foreach($cardTypes as $card){
  24.   // Add all of each type of card to the deck
  25.   $quantity = $card['qty'];
  26.  
  27.   // Get rid of the qty for the deck cards
  28.   unset($card['qty']);
  29.  
  30.   // Create the deck
  31.   for($x = 0; $x < $quantity; $x++){
  32.     $deck[] = $card;
  33.   }
  34. }
  35.  
  36. // Randomize the deck
  37. shuffle($deck);
  38.  
  39. // Cut the deck down to size
  40. $deck = array_slice($deck, 0, $deckSize);
  41.  
  42. // Check if there are enough cards in the deck
  43. if( ($hands * $cardsInHand) > count($deck)) {
  44.   throw new Exception('Not enough cards in deck');
  45. }
  46.  
  47. // Deal out hands
  48. for($x = 0; $x < $hands; $x++) {
  49.   for($y = 0; $y < $cardsInHand; $y++) {
  50.     $hand[$x][] = array_shift($deck);
  51.   }
  52. }  
  53.  
  54. // Dump it all out and see
  55. echo "<h2>Hand 1</h2>";
  56. foreach($hand[0] as $card) {
  57.     echo "<img src=\"{$card['img']}\" width='50'>";
  58. }
  59. echo "<hr>";
  60. echo "<h2>Hand 2</h2>";
  61. foreach($hand[1] as $card) {
  62.     echo "<img src=\"{$card['img']}\" width='50'>";
  63. }
  64. echo "<hr>";
  65. echo "<h2>Remaining Deck</h2>";
  66. foreach($deck as $card) {
  67.     echo "<img src=\"{$card['img']}\" width='50'>";
  68. }
File Description
  • card game
  • PHP Code
  • 18 Feb-2020
  • 1.67 Kb
You can Share it: