1 回答

TA贡献1829条经验 获得超13个赞
正如 wubbler 在他的评论中提到的那样,用于创建随机密码的字符与用于猜测密码的字符之间似乎存在差异。
去创造:
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
猜测:
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
当随机生成的密码包含任何数字时,这会导致程序无法猜测密码。通过将数字添加到可猜测的字符中,程序会更加一致地成功。
至于请求:
我希望控制台在猜到错误字符后不要尝试它们
您可以通过为每个索引保留一个可猜测字符的集合来实现此目的,然后在猜测到给定索引后从它的集合中删除一个字符。下面的代码满足了这一点:
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
string intro6 = "How many characters in the password? (USE INTEGERS)";
foreach (char c in intro6)
{
Console.Write(c);
Thread.Sleep(50);
}
Console.WriteLine("");
string delta = Console.ReadLine();
try
{
int passwordlength = Convert.ToInt32(delta);
// BARRIER
string password = RandomString(passwordlength);
Random r = new Random();
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
List<string> dictionary = new List<string>(new string[] { password });
string word = dictionary[r.Next(dictionary.Count)];
List<int> indexes = new List<int>();
Console.ForegroundColor = ConsoleColor.Red;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.Length; i++)
{
sb.Append(letters[r.Next(letters.Length)]);
if (sb[i] != word[i])
{
indexes.Add(i);
}
}
Console.WriteLine(sb.ToString());
var charsToGuessByIndex = indexes.ToDictionary(k => k, v => letters);
while (indexes.Count > 0)
{
int index;
Thread.Sleep(10);
Console.Clear();
for (int i = indexes.Count - 1; i >= 0; i--)
{
index = indexes[i];
var charsToGuess = charsToGuessByIndex[index];
sb[index] = charsToGuess[r.Next(charsToGuess.Length)];
charsToGuessByIndex[index] = charsToGuess.Remove(charsToGuess.IndexOf(sb[index]), 1);
if (sb[index] == word[index])
{
indexes.RemoveAt(i);
}
}
var output = sb.ToString();
for (int i = 0; i < output.Length; i++)
{
if (indexes.Contains(i))
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.Cyan;
}
Console.Write(output[i]);
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.Green;
string outro1 = "Password successfully breached. Have a nice day.";
foreach (char c in outro1)
{
Console.Write(c);
Thread.Sleep(20);
}
Console.WriteLine("");
Thread.Sleep(100);
Console.ReadLine();
}
catch
{
if (delta is string)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Clear();
Console.WriteLine("FATAL ERROR PRESS ENTER TO EXIT");
Console.ReadLine();
}
else
{
Console.WriteLine("welp, it was worth a try.");
Console.ReadLine();
}
}
}
charsToGuessByIndex跟踪每个索引可以猜测哪些字符,并在猜测字符的 for 循环内相应地更新:
charsToGuessByIndex[index] = charsToGuess.Remove(charsToGuess.IndexOf(sb[index]), 1);
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报