使用 C# 控制台应用程序。该代码旨在通过字母随机循环以尝试查找密码。当一个字母与密码中的一个字母匹配时,它将一直存在,直到所有字母都匹配。现在,我使用“算法”作为占位符。默认情况下,字母是红色的。但是,我希望特定字符在匹配时将它们的(并且只有它们的)前景色更改为绿色。尚未匹配的颜色应保持红色。using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApp3{ class Program { // let's figure out how to make specific letters a specific colour. // if not letter, RED. if letter, CYAN. static void Main(string[] args) { Random r = new Random(); string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; List<string> dictionary = new List<string>(new string[] { "ALGORITHM" }); 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()); while (indexes.Count > 0) { int index; Thread.Sleep(100); Console.Clear(); for (int i = indexes.Count - 1; i >= 0; i--) { index = indexes[i]; sb[index] = letters[r.Next(letters.Length)]; if (sb[index] == word[index]) { indexes.RemoveAt(i); } } Console.WriteLine(sb.ToString()); } Console.ReadLine(); } }}
1 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
如果你想写不同颜色的字符,你需要在写每个字符之前改变颜色。例如,在您的情况下,您可以将最后一个替换为Console.WriteLine(sb.ToString());:
var output = sb.ToString();
for (int i = 0; i < output.Length; i++)
{
if (indexes.Contains(i))
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
}
Console.Write(output[i]);
}
Console.WriteLine();
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报
0/150
提交
取消
