Search code examples
phppoker

How do I compare two randomly picked arrays with earlier picks?


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?


Solution

  • 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.