Im making a simple poker script in PHP and up to the point where im analysing the players hand of 5 cards.
I have the hand stored in an array ($hand) like:
Array (
[0] => Array (
[face] => k
[suit] => d
)
[1] => Array (
[face] => 6
[suit] => s
)
[2] => Array (
[face] => 6
[suit] => h
)
[3] => Array (
[face] => 4
[suit] => d
)
[4] => Array (
[face] => 7
[suit] => h
)
)
I’m not sure how to start of with finding results. For example how would I find out if the player has FOUR OF A KIND, or 4 cards with the same face?
Or if the player gets a RUN of consecutive faces (3,4,5,6,7)?
(I’m not very good at arrays)
The four-of-a-kind is simple enough. You loop over your array of cards, and add up how many of each face you have:
This would give you
You then search this new array to see if any of the values are 4. If you have a 4, then you’ve got a 4-of-a-kind. In this case, you’ve got a single two-of-a-kind and a bunch of singles.
For the consecutive runs, you’d need to sort the original array by suit, then by face, so you get all the diamonds together, all the hearts together, etc… and within each suit, the invididual cards are in ascending order. Then a simple “state machine” to check if you’ve got a run of 5. Assuming that your hand array is already sorted, and that the ‘face’ cards are represented by numerical values (‘j’ -> 10, ‘q’ => 11, ‘k’ => 12, ‘a’ => 13):