我目前正在课堂外开展一个简单的谜语游戏,而我想做的是有一个声明可以验证问题是什么,以及输入的答案是否正确。这是我到目前为止的代码:
private void butt_Submit_Click(object sender, EventArgs e)
{
if (lab_Riddle.Text == "What Walks on 4 Legs in the Morning, 2 in the Afternoon and 3 in the Evening?")
if (TeBo_Ans.Text == "A Man") ;
; {
MessageBox.Show("Well Done");
lab_Riddle.Text = ("I have an Eye but Cannot See- What Am I?");
}
if (TeBo_Ans.Text == "Mankind") ;
{
MessageBox.Show("Good Words");
lab_Riddle.Text = ("I have an Eye but Cannot See- What Am I?");
}
if (TeBo_Ans.Text == "People") ;
{
MessageBox.Show("Yes");
lab_Riddle.Text = ("I have an Eye but Cannot See- What Am I?");
}
if (TeBo_Ans.Text == "A Person") ;
{
MessageBox.Show("Exactly");
lab_Riddle.Text = ("I have an Eye but Cannot See- What Am I?");
}
if (TeBo_Ans.Text == "Humankind") ;
{
MessageBox.Show("Exactly");
lab_Riddle.Text = ("I have an Eye but Cannot See- What Am I?");
}
}
此处,lab_Riddle
是包含问题的标签,TeBo_Ans
是用户键入答案的文本框。这段代码是Works,但理想情况下我想把它压缩成类似
If lab_Riddle.Text= [Riddle 1]
{
If TeBo_Ans == [a] OR [b] OR [d]
{
MessageBox.Show ("Correct")
lab_Riddle.Text [riddle 2]
}
Else
{
MessageBox.Show ("Incorrect")
}
}
语言是C#,如果我还没有说过,和垂直线。这可能是一个非常漫长而复杂的方式,但我仍然很擅长编码。
答案 0 :(得分:2)
你可以使用字典作为答案
,例如
String answer = "a dog";
Dictionary<string, string> riddleans = new Dictionary<string, string>();
riddleans.Add("a man", "Well done");
riddleans.Add("mankind", "Good words");
answer = answer.ToLower();
if (riddleans.ContainsKey(answer))
{
Messagebox.Show(riddleans[answer]);
gotonextriddle();
}
else
{
Messagebox.Show("Incorrect);
}
但你可以通过使用结构或类来扩展它,然后你有一个谜语列表等等。
有一点需要指出的是答案 - 它意味着如果我写“mankind”或“mankind”而不是“人类”,它仍然适合。
答案 1 :(得分:0)
由于您要根据用户输入的内容显示不同的文本,因此可以将其存储在Dictionary
var answers = new Dictionary<string, string>()
{
{ "Mankind", "Good words" },
{ "People", "Yes" },
{ "A Man", "People" }
};
var answerGiven = TeBo_Ans.Text;
if (answers.ContainsKey(answerGiven))
{
// user has the correct answer
}
显然,在这种情况下,你需要考虑区分大小写,但这只是一种做你想做的事情。我想在某些方面,你的问题可能会更好地放在Code Review Stack Exchange上。