【问题标题】:Remove an int from a list for a deck of cards从一副牌的列表中删除一个 int
【发布时间】:2015-09-14 21:26:38
【问题描述】:

我正在尝试在 Visual Studio 中制作纸牌游戏。我坚持的功能是从牌组(列表)中取出一张牌。我使用以下与按钮单击相关的随机数函数。

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

问题是在我再次按下按钮后,它并没有从列表中删除 int,列表只是回到我删除 int 之前的状态。我将如何从列表中永久删除 int ?

【问题讨论】:

  • 将您的Int 更改为int 有区别.. 或使Int Int32 Int 不是C# 中的数据类型,但int 是..您还需要将Deck 定义为全局列表
  • 你有一个索引?也许你想要的是 removeAt 方法。

标签: c#


【解决方案1】:

因为您已经在Button_Click 事件中定义了列表,所以每次单击Button 时都会重新创建列表。你应该让它全球化:

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);
}

【讨论】:

  • 即使卡片与索引匹配,removeAt 不是比 remove 快吗? stackoverflow.com/questions/3211679/…
  • 是的,它只是有时会删除一些东西,但我将它切换到 RemoveAt 并且“现在”它工作得很好。
【解决方案2】:

您必须使列表对表单具有全局性,这样您就不会在每次单击按钮时都创建一个新列表。否则只有在执行按钮单击方法时,列表才会存在。

您还应该只创建一次Random 类。

如果你将列表初始化放在它自己的方法中,你可以在表单构造函数中调用它,也可以在另一个按钮中单击以重新开始游戏。

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};
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2019-04-18
    • 1970-01-01
    • 2022-06-17
    • 2013-09-20
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多