0

I'm trying to create a version of a poker, where the program hands out 2 cards to each player (6 of them). I've come up with a program that can pick 1 random card for every player, but the problem is that sometimes, 2 players get the same card. My attempt to solve this problem was by giving every loop a diffrent value based on the cards place in the array + the loops value, and then comparing it to earlier loops, but without any sucess...

Here is my currently "working" program:

<?php

$colour = array('Heart', 'Diamonds', 'Spades', 'Clubs');
$card = array('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King');

for($i=1; $i<=6;$i++)
{

$m = 0;
$n = 0;

$random1 = array_rand($card);
echo $card[$random1];
$m = $card[$random1];

$random2 = array_rand($colour);
echo " ". $colour[$random2];
$n = $colour[$random2];

}
?>

How should I continue? Is there an easier way to do this?

FilipLIS
  • 3
  • 5

2 Answers2

0
$Cards=array();

while(count($Cards)<(2*6)){    
    $colour = array('Heart', 'Diamonds', 'Spades', 'Clubs');
    $card = array('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen');

    shuffle($card);
    $m = array_shift($card);

    shuffle($colour);
    $n = array_shift($colour);

    echo $card = $m."/".$n;
    $Cards[$card]=$card;
    echo '<br>';
}
$Cards=array_values($Cards);

echo '<pre>';
var_export($Cards);#2 unique cards for each player in array

Just a Way.

JustOnUnderMillions
  • 3,741
  • 9
  • 12
  • Unless I'm reading it wrong... Since you're initialising the arrays within each iteration of the loop, it's possible to have the same card twice. But if you moved the initialisation out of the loop, then you'd use up your `$colour` array after just four iterations - you could never have more than one card of each suit *or* rank dealt more than once, e.g. once Ace of Hearts is dealt, no more Aces or Hearts would be... – komodosp May 18 '16 at 07:59
0

You could always do it like a real deck of cards, rather than two arrays, one array, containing all cards from Ace - King in each suit

e.g.

$cards = array('AH', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H',
               'TH', 'JH', 'QH', 'KH', 'AD', '2D', '3D', '4D', '5D',
               '6D', '7D', '8D', '9D', 'TD', 'JD', 'QD', 'KD', 'AC',
               '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', 'TC',
               'JC', 'QC', 'KC', 'AS', '2S', '3S', '4S', '5S', '6S',
               '7S', '8S', '9S', 'TS', 'JS', 'QS', 'KS');

// then the appropriately named... 

shuffle($cards);

// then "deal" the cards by looping through the array from the beginning!

$i = 0; 

for ($player = 0; $player < 6; $player ++) {
   echo "<br />Player $player : Card 1 = " . $cards[$i++];
   echo " Card 2 = " . $cards[$i++];
}

You could have a separate function to translate the "AH", "9S", etc. into the actual names of the cards, or actually set them with their display names at the time of creating the array.

komodosp
  • 3,316
  • 2
  • 30
  • 59