简体   繁体   中英

Remove an int from a list for a deck of cards

I'm trying to make a card game in visual studio. The function I'm stuck on is taking a card out of the deck (the list). I use the following random number function tied to a button click.

List<int> Deck = new List<int> { 0, 1, 2, 3};
Random R = new Random();
Int Card = R.Next(Deck.Count);
Deck.Remove(Card);

The problem is after I press the button again it doesn't remove the int from the list, the list just goes back to how it was before I removed the int. How would I go about removing the int from the list permanently?

Because you have defined the list in Button_Click event and so every time you click the Button the list is created again. You should make it global:

List<int> Deck = new List<int> { 0, 1, 2, 3};//global

private void button1_Click(object sender, EventArgs e)
{
   Random R = new Random();
   int Card = R.Next(Deck.Count);
   Deck.Remove(Card);
}

You must make the list global to the form, so that you don't create a new list each time you click the button. Otherwise the list will exist only as long as the button click method is executing.

Also you should create the Random class only once.

If you place the list initialization in its own method, you can call it in the form constructor, as well as in another button click in order to restart the game.

public partial class frmCardGame : Form
{
    // Fields declared here exist as long as the form is open.
    private readonly Random R = new Random();
    private List<int> Deck;

    public frmCardGame()
    {
        InitializeComponent();
        InitializeDeck();
    }

    private void btnPlay_Click(object sender, EventArgs e)
    {
        // Variables declared here exist only as long as this method is being executed.
        int card = R.Next(Deck.Count);
        Deck.Remove(card);
    }

    private void btnRestart_Click(object sender, EventArgs e)
    {
        InitializeDeck();
    }

    private void InitializeDeck()
    {
        Deck = new List<int> { 0, 1, 2, 3};
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM