Add images to array, pick one at random and delete

2019-09-21 22:35发布

问题:

So I just started programming in C# (I do know the basics though). With friends I sometimes play a card game where you have to pick a card and according to what's on it, we have to do a challenge and the loser has to take a drink. Just for fun, I want to make this game as a Windows Form Application. I'm having issues with the images though. I want to get them from a folder that's in the directory of the program executable and add them to an array. Then I want to randomly select one (with the Random class) when a button is clicked. Once a card has been picked, I want it to be deleted from the array so it can't be chosen again.

I've been looking through quite a bit of tutorials on SO and other places, but I can't find something that fully works. This one came closest, as it did select a random picture when a button was clicked and displayed it, but I didn't find a way to remove that picture from the array. How can I add the functionality to delete the image from the array?

Edit: I should've added that I've already tried some stuff that didn't work. I deleted that code though ('cause it didn't work), but I'll try some stuff again and post back when I can't make it work.

回答1:

According to the link in your example i will assume that in your code you represent an image as string.

Just use a list List<string> images = new List<string>(); to hold your images

to add elements in the list use images.Add(elemenet) where element is of type string

to draw a randrom card use

Randrom randomNumber = new Random();
int extractedCard = randomNumber.Next(images.Length);

then display images[extractedCard]

and then you can easily remove that card from the list images.RemoveAt(extractedCard)



标签: c# arrays random