dimanche 6 juin 2021

Whenever I insert values to an array with Random all the indexes have the same result [duplicate]

I need to make an array with cards for a memory game. Each card have a color and a letter. I put all the cards in an array that called: "BoardCards", and I want to reset all the indexes with a random color and letter. Here's my code:

public static BasicCard[] ResetBoard()
{
    BasicCard[] boardCards = new BasicCard[10];
    for (int i = 0; i < boardCards.Length; i++)
    {
        Random rand = new Random();
        int color = rand.Next(1, 16);
        int letter = rand.Next(65, 91);
        boardCards[i] = new IconColorCard((ConsoleColor)color, (char)letter);
    }
    return boardCards;
}

The weird thing is - when I try to debug it step by step the cards doesn't look the same. But when I press Ctrl+F5 - they look the same. And if I don't use the Random , they don't look the same in any way, so that's what I think is causing the problem.

It's working when I reset the indexes like that for example:

boardCards[0] = new IconColorCard(ConsoleColor.Red, 't');
boardCards[1] = new IconColorCard(ConsoleColor.Yellow, 'y');

Can I fix it when I still use the Random in my code?




Aucun commentaire:

Enregistrer un commentaire