The amazing game the Cornball is about to be ported to C#.NET. A project which is a lot easier than expected. The number of hours I put down so far is barely hitting two digits and still I have reached a playable alpha version. The source will be published in parts or in its entirety when I am finished, but until then there is one small problem I would like to show that required some extra thought.
The class structure consists of Card and Deck, which inherits List<Card>. Deck has a Shuffle method which utilizes the Fisher-Yates algorithm.
In the middle of the game, only a part of the game should be re-shuffled, which renders this method useless. Long story short, I came up with the following solution. Each card has a boolean property, IsInOrder, which specifies whether the card is in its correct place or not. To mix the incorrectly placed cards I just find the indices for them and use that as a base for the re-shuffle.
The class structure consists of Card and Deck, which inherits List<Card>. Deck has a Shuffle method which utilizes the Fisher-Yates algorithm.
public void Shuffle() { Random random = new Random(); for(int i = Count - 1; i >= 0; i--) { Swap(random.Next(i), i); } } internal void Swap(int fromIndex, int toIndex) { Card temp = this[fromIndex]; this[fromIndex] = this[toIndex]; this[toIndex] = temp; }
In the middle of the game, only a part of the game should be re-shuffled, which renders this method useless. Long story short, I came up with the following solution. Each card has a boolean property, IsInOrder, which specifies whether the card is in its correct place or not. To mix the incorrectly placed cards I just find the indices for them and use that as a base for the re-shuffle.
public void Reshuffle() { List shuffle = new List(); for(int i = 0; i < Count; i++) { if(!this[i].IsInOrder) { shuffle.Add(i); } } Random random = new Random(); for(int i = shuffle.Count - 1; i >= 0; i--) { Swap(shuffle[random.Next(i)], shuffle[i]); } }
Comments
Post a Comment