这是一个刽子手程序,如果我猜的单词只包含一个字母一次,但如果它再次包含一个或多个字母,当我再次单击该字母时没有任何反应,它可以正常工作。
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');
}
更新:我找到了我的问题的解决方案,并在下面将其发布为答案。
答案 0 :(得分:2)
用
替换你的其他人的身体var indexes = AllIndexesOf(myWords[randomNum].guess_word,letter);
foreach(int i in indexes)
astericksBox.Text = astericksBox.Text.Remove(i,1).Insert(i,letter.ToString());
并创建此功能(我从Finding ALL positions of a substring in a large string in 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);
}
}
答案 1 :(得分:1)
替换它:
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);
该代码也更容易阅读。
答案 2 :(得分:1)
我将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;
}