[英]Hangman game: error if the quessword contains a letter more than once
这是一个适用于hangman程序的程序,如果我猜的单词只包含每个字母一次,则效果很好,但是当我再次单击该字母时,如果它包含一个或多个字母两次,则效果很好。
private void charGuess(char letter )
{
if (!myWords[randomNum].guess_word.Contains(letter))
{
totalWrongGuesses(letter);
}
else
{
int tempIndex = myWords[randomNum].guess_word.IndexOf(letter);
astericksBox.Text = astericksBox.Text
.Remove(tempIndex,1)
.Insert(tempIndex,letter
.ToString());
}
if (!astericksBox.Text.Contains("*"))
{
MessageBox.Show("You've Won!!");
}
}
private int randomNumGenerator()
{
int rndNum; // a variable to temporarily store the random number generated
Random randomNum = new Random(); // creates a new Random object randomNum
return rndNum = randomNum.Next(0,19); // returns a randomNum vlue between 0 and 19
}
private void button15_Click(object sender, EventArgs e)
{
charGuess('a');
}
更新:我找到了解决问题的方法,并将其发布为下面的答案。
用其他东西代替你的身体
var indexes = AllIndexesOf(myWords[randomNum].guess_word,letter);
foreach(int i in indexes)
astericksBox.Text = astericksBox.Text.Remove(i,1).Insert(i,letter.ToString());
并创建此函数(这是我在C#中的大字符串中找到子字符串的所有位置后得到的)
public static List<int> AllIndexesOf(this string str, string value)
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0; ; index += value.Length)
{
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
替换为:
int tempIndex = myWords[randomNum].guess_word.IndexOf(letter);
astericksBox.Text = astericksBox.Text.Remove(tempIndex,1).Insert(tempIndex,letter.ToString());
有了这个:
int tempIndex = 0;
do
{
tempIndex = myWords[randomNum].guess_word.IndexOf(letter, tempIndex);
astericksBox.Text = astericksBox.Text.Remove(tempIndex,1).Insert(tempIndex,letter.ToString());
tempIndex++;
}
while (tempIndex > 0);
为了提高效率/性能,我可以这样做:
int tempIndex = 0;
var mask = astericksBox.Text.ToCharArray();
do
{
tempIndex = myWords[randomNum].guess_word.IndexOf(letter, tempIndex);
mask[tempIndex] = letter;
tempIndex++;
}
while (tempIndex > 0);
astericksBox.Text = new string(mask);
该代码阅读起来也容易得多。
我将charGuess中的else语句更改为以下代码,它现在可以按预期工作。
else
{
int tempIndex = myWords[randomNum].guess_word.IndexOf(letter);
String tempWord = myWords[randomNum].guess_word;
astericksBox.Text = astericksBox.Text.Remove(tempIndex,1).Insert(tempIndex,letter.ToString());
tempWord = tempWord.Remove(tempIndex, 1).Insert(tempIndex, "£");
myWords[randomNum].guess_word = tempWord;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.