C#猜词游戏修复请求:字符全揭晓后无法限制最大尝试次数
问题解决:猜词游戏字符全揭晓后限制最大尝试次数
你的核心问题是当所有目标字符都被揭晓后,没有终止游戏的逻辑,同时原代码里还有几个逻辑偏差(比如第一次失败就直接揭第一个字符,不符合每5次失败揭一个的需求;用浮点型计算次数容易出精度问题)。下面是修复后的完整代码,附带关键修改说明:
修复后的代码
internal class Program { private static void Main(string[] args) { List<string> wordList = new List<string> { "Text", "Test", "Report", "Elephant", "GingerCat", "Cute", "Beach" }; Random r = new Random(); int index = r.Next(wordList.Count); string targetWord = wordList[index]; // 注释调试用的目标词输出,正式游戏隐藏答案 // Console.WriteLine(targetWord); PlayGuessGame(targetWord); } static void PlayGuessGame(string targetWord) { string playerGuess = null; int attempts = 0; int revealedLettersCount = 0; int maxFinalAttempts = 3; // 所有字符揭晓后额外给3次尝试机会 bool gameOver = false; Console.WriteLine("欢迎来到猜词游戏!"); while (!gameOver) { Console.WriteLine("\n请输入你的猜测:"); playerGuess = Console.ReadLine(); attempts++; // 猜对的情况 if (playerGuess.Equals(targetWord, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"太棒了!你用了{attempts}次就猜对了!"); gameOver = true; continue; } Console.WriteLine($"猜错了,这是你第{attempts}次尝试"); // 每5次失败揭晓一个字符 if (attempts % 5 == 0 && revealedLettersCount < targetWord.Length) { revealedLettersCount++; Console.WriteLine($"揭晓第{revealedLettersCount}个字符:{targetWord[revealedLettersCount - 1]}"); // 展示已揭晓的所有字符 Console.Write("已揭晓的字符:"); for (int i = 0; i < revealedLettersCount; i++) { Console.Write($"{targetWord[i]} "); } Console.WriteLine(); } // 所有字符都已揭晓后,限制剩余尝试次数 if (revealedLettersCount == targetWord.Length) { maxFinalAttempts--; if (maxFinalAttempts <= 0) { Console.WriteLine($"游戏结束!你用完了所有机会,目标单词是:{targetWord}"); gameOver = true; } else { Console.WriteLine($"所有字符都已揭晓,你还有{maxFinalAttempts}次机会"); } } } } }
关键修改说明
- 修正字符揭晓逻辑:原代码第一次失败就揭第一个字符,现在改为**每5次尝试失败(即attempts是5的倍数)**才揭晓一个字符,匹配你的需求。
- 补上游戏终止逻辑:当所有字符都揭晓后,启动剩余尝试次数计数,用完后直接终止游戏并展示目标词。
- 替换浮点型计数:用
int类型记录尝试次数,避免浮点运算的精度误差。 - 优化游戏体验:
- 添加已揭晓字符的统一展示,让玩家更清晰掌握线索
- 支持忽略大小写的猜测判断(可根据需求去掉
StringComparison.OrdinalIgnoreCase) - 变量命名更直观,代码结构更易读
内容的提问来源于stack exchange,提问作者itay0246
相关产品推荐
相关产品推荐

