1 回答

TA貢獻1829條經(jīng)驗 獲得超13個贊
正如 wubbler 在他的評論中提到的那樣,用于創(chuàng)建隨機密碼的字符與用于猜測密碼的字符之間似乎存在差異。
去創(chuàng)造:
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
猜測:
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
當隨機生成的密碼包含任何數(shù)字時,這會導致程序無法猜測密碼。通過將數(shù)字添加到可猜測的字符中,程序會更加一致地成功。
至于請求:
我希望控制臺在猜到錯誤字符后不要嘗試它們
您可以通過為每個索引保留一個可猜測字符的集合來實現(xiàn)此目的,然后在猜測到給定索引后從它的集合中刪除一個字符。下面的代碼滿足了這一點:
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 循環(huán)內(nèi)相應地更新:
charsToGuessByIndex[index] = charsToGuess.Remove(charsToGuess.IndexOf(sb[index]), 1);
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報