【问题标题】:C# How to match items from two list boxesC#如何匹配两个列表框中的项目
【发布时间】:2023-03-24 23:05:02
【问题描述】:

我正在尝试使用两个列表框创建匹配列游戏。例如,当用户单击第一个列表框中的数字 100 时,他们需要单击第二个列表框中与该数字匹配的动物。一旦所有列都匹配,我想向用户显示一条消息,告诉他们他们有多少答案是正确的。我也知道使用字典是一种更好的方法,但是我不确定如何用我的列表框正确实现它并随机化它

*我面临的问题

  • 我的列表框正在添加重复值

*我需要什么帮助

  • 为动物分配编号
  • 通过单击两个列表框来匹配项目
  • 在末尾显示一条消息,指出正确答案的数量

代码:

public partial class game : Form
{
    
    public static List<string> animals = new List<string> { "cat", "dog", "bird", "frog", "snake", "duck", "tiger" };
    public static List<string> values = new List<string> { "400", "200", "300", "800", "100", "500", "600"};

    public game()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        listBox2.Items.Clear();

        //random class created
        Random random = new Random();
      
        for (var i = 0; i < 4; i++)
        {
            int index = random.Next(values.Count);
          
            //adds numbers to listbox
            listBox1.Items.Add(values[index]);                                
        }
        for (var i = 0; i < 7; i++)
        {         
            int index = random.Next(animals.Count);

            //adds animals to listbox          
            listBox2.Items.Add(animals[index]);
        }
    }
    
}

【问题讨论】:

  • 你的意思是要随机连接两个大小相同的不同列表?

标签: c# string winforms listbox


【解决方案1】:
private static Dictionary<string, string> test = new Dictionary<string, string>() {
      {
        "100",
        "dog"
      },
      {
        "200",
        "cat"
      },
      {
        "300",
        "bird"
      },
      {
        "400",
        "parrot"
      },
    };

    public Form1() {
      InitializeComponent();
    }
    
    private void Form1_Load(object sender, EventArgs e) {
      foreach(KeyValuePair < string, string > kvp in test) {
        listBox1.Items.Add(kvp.Key);
        listBox2.Items.Add(kvp.Value);
      }
    }
    
    private void listBox2_SelectedValueChanged(object sender, EventArgs e) {
      if (test[listBox1.Text] != listBox2.Text) {
        MessageBox.Show("Incorrect");
      }
      else {
        MessageBox.Show("Correct");
      }
    }
  

这里的额外好处是我们使用字典来填充列表框,因此我们不必在 UI 中管理集合。另外不要忘记在 listbox2

上为 SelectedValueChanged 添加事件监听器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 2022-12-17
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多