Last week I played around and made a very simple Unity app that deals 2x 5 card Poker hands. The main reason for the exercise was to familiarize myself a bit more with stuff like enums, structs, arrays, lists, etc. in C# in Unity.
I know all those things, but I needed some practice to get it to do what I want in C# (was really easy in PHP haha!).
Anyway, Jayson helped me a bit, and I got it right in the end. The one thing I want to share though, is the simple sorting algorithm I used to put your hand in order from low card to high card. There are many sorting algorithms out there, some way more efficient than others. A very simple one is the Selection Sort. It's not the best one to use if you have huge lists of items that needs sorting, but for a small list, like 5 cards, it's a great and simple way to get the job done.
Check out the explanation for it here: http://en.wikipedia.org/wiki/Selection_sort
And, here's the loop structure I used in my C# script:
for (int i = 0; i < playerHand.Count; i++)
{
int j = i;
for (int k = i+1; k < playerHand.Count; k++)
{
if (playerHand[k].value < playerHand[i].value)
{
j = k;
Card tempHand = playerHand[i];
playerHand[i] = playerHand[j];
playerHand[j] = tempHand;
}
}
}
playerHand is the list containing the five cards (and each card has a value property that I use - for example, a two's value is 2, a Jack's value is 11, etc).
As you can see, if the list gets huge, then this will take forever because the loop is essentially running through the whole list over and over again, with each new run being one item less...
Basically, here's how it works. I take the first card, and run through the remaining cards and check their values against the first card. If I find a lower valued card, I swap the two around. Now I move on to the second card, and check again on the remaining cards to see if I can find one with a lower value, and if so, swap them around. I carry on like this until I reach the end. For a Poker hand, you don't need anything more in my opinion. Sorting them in this fashion also makes it a lot easier to analyze the hands!
And see, it works:
I've also made the script analyze the hand and display what it is. This was actually a lot easier than I thought - you basically start at the best Poker hand, which is a Straight Flush - test for that - if it's not one, test for the next best hand, a Straight Flush. Then Four-of-a-Kind. The Full House, Flush, Straight, Three-of-a-Kind, Two Pairs, Single Pair and lastly nothing. If you do it this way around, you don't have to worry about over complicating things when you test for the weaker hands... :)
Anyway, hope you find this helpful!
No comments:
Post a Comment