I was playing around with building a card game engine and ran across something interesting. My solution as I found all over the internet was to use Random() to generate a random number and use that to "order" the list (array) representing the deck.
My "test" game was basically high card where each player had a deck and drew a card. The person with the highest card won the hand. As I ran the test either Player 1 won or the game was a draw. Player 2 never won.
As it turns out Random is not very good at generating random numbers. It uses a fixed algorithm such that the result are very predictable. Also, it is an expensive operation as it is not very efficient.
A sort is actually a better solution and using sometime to generate random unique values works better. I don't take credit for this code but here is an example of the better implementation:
var cards = Enumerable.Range(0, 51);
var shuffledcards = cards.OrderBy(a => Guid.NewGuid());
Friday, October 25, 2013
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment