[英]C# How to match items from two list boxes
我正在嘗試使用兩個列表框創建匹配列游戲。 例如,當用戶單擊第一個列表框中的數字 100 時,他們需要單擊第二個列表框中與該數字匹配的動物。 一旦所有列都匹配,我想向用戶顯示一條消息,告訴他們他們有多少正確的答案。 我也知道使用字典會是一個更好的方法,但是我不確定如何使用我的列表框正確實現它並隨機化它
*我面臨的問題
*我需要什么幫助
給動物賦值
通過單擊來匹配兩個列表框之間的項目
在最后顯示一條消息,指示有多少答案是正確的
公共部分類游戲:形式{
public static List<string> animals = new List<string> { "cat", "dog", "bird", "frog", "snake", "duck", "tiger" };
public static List values = new List { "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]);
}
}
}
}
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添加一個事件監聽器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.