I’m trying to make a basic card matching game, and I’m making a basic AI for the game. I need the AI to pick from a list of 16 cards. However after cards get removed my AI is still searching for them.CardPicker = Random.Range (1, 16);
That’s what i’m using. So the AI will keep on looking for cards until it finds the one’s left. Which takes awhile when there is only two cards left to find. Is there a random way to pick from a list of values. Such as (1,2,3,4,5,6,7 and so on) so when a card is removed I can remove one of the numbers?
using System.Collections.Generic;
...
List<int> CardPicker;
// This will make a list of all cards
void MakeList()
{
CardPicker = new List<int>();
for (int i = 1; i <= 16; ++i)
{
CardPicker.Add(i);
}
}
// This will return a random card that hasn't been used yet
int RandomCard()
{
// Return a bad card if the list wasn't made yet
if (CardPicker == null) return -1;
// Return a bad card if the list is already empty
if (CardPicker.Count <= 0) return -1;
// Return a random card that's left and remove it so we don't pick it again
int PickedCardIndex = Random.Range(0, CardPicker.Count);
int PickedCard = CardPicker[PickedCardIndex];
CardPicker.RemoveAt(PickedCardIndex);
return PickedCard;
}
Once your list is randomized, you’ll just loop through it picking the first card, then the second, then the third. etc. Since the list will be random, it will still appear you’re picking a random card from the list each time, but you don’t have to loop through it trying to hit that one card you hadn’t picked. Nor do you have to remove stuff from the list. You can just randomize it again when you want to.
Just remember you’ll have to add using System.Linq;
And you’ll need to declare your random as
System.Random rnd = new System.Random(); or else it will try to use unity’s random instead.
And here, to add how you might do it slightly modified
List<int> myList = new List<int>();
for(int x = 1;x < 16;x++)
{
myList.Add(x);
}
System.Random rnd = new System.Random();
var randomizedList = (from item in myList
orderby rnd.Next()
select item).ToList<int>();
print(randomizedList[0]);