我创建了一个非常简单的刽子手游戏,要求用户输入一个字母作为猜测。用户第一次输入正确的猜测时,游戏会记录下来,并且控制台会显示正确的字母。但是,随着每个后续的正确猜测,我为解决方案创建的数组显然没有更新,并且控制台没有写出第二个正确的猜测。此外,用户不会因为每次猜错而失去生命。
任何人都可以了解我出错的地方吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Hangman2
{
class Program
{
static string[]letters = {"a","e","r","o","p","l","a","n","e"};
static int Lives = 7;
static string Gu = ""; // this is not being updated with each guess
static string[]Solution = new string[letters.Length];
public static void Main(string[] args)
{
FillSolution();
UserGuess();
while (Lives > 0) {
UserGuess();
}
Console.ReadLine();
}
static void FillSolution()
{
string star = "*";
for(int i = 0; i < Solution.Length; i++) {
Solution[i] = star;
}
}
static void UserGuess()
{
Console.WriteLine("Please enter your guess");
string Guess = Console.ReadLine();
Gu += Guess; //this isn't working
bool GuessRight = false;
for(int i = 0; i<letters.Length; i++) {
string y = letters[i];
if(Gu == y) {
Solution[i] = letters[i];
GuessRight = true;
}
else {
GuessRight = false;
}
if(GuessRight = false) {
Lives--; // this is also not working
}
}
DisplaySolution();
}
static void DisplaySolution()
{
for(int i = 0; i < Solution.Length; i++) {
Console.Write(Solution[i]);
}
Console.WriteLine("You have " + Lives + " lives remaining");
}
}
}
答案 0 :(得分:4)
您的if语句正在使用赋值运算符,而不是检查它是否等于false
if(GuessRight = false){
应该是
if(GuessRight == false){
或只是
if(!GuessRight){
此外,您当前检查的整个if语句是错误的,您需要查找解决方案是否有猜测而不是串联到您的Gu
字符串(不需要)< / p>
var idx = Array.IndexOf(letters, Guess);
if(idx >= 0){
while(idx >= 0){
Solution[idx] = Guess;
idx = Array.IndexOf(letters, Guess);
}
}
答案 1 :(得分:1)
我注意到的第一个问题是第72行,你写道:
if (GuessRight = false)
这是有问题的原因是因为您试图将GuessRight变量的值设置为false(您之前已经完成),而您要检查GuessRight
是否等于false ==
“这是相等运算符。该行应为:
if (GuessRight == false)
答案 2 :(得分:1)
以下内容应该可以解决您的一些生活计数问题。我不确定为什么字符串连接目前不适合你。
static void UserGuess()
{
Console.WriteLine("Please enter your guess");
string Guess = Console.ReadLine();
Gu += Guess; // this should work
bool GuessRight = false;
for(int i = 0; i<letters.Length; i++){
string y = letters[i];
if(Gu == y) {
Solution[i] = letters[i];
GuessRight = true;
}
else {
GuessRight = false;
}
if(GuessRight == false) {// Have to use '==' when comparing, '=' will assign the value
Lives--;
}
}
DisplaySolution();
}
答案 3 :(得分:0)
所以,我第一次'for'循环出错的地方就到了第78行。 感谢大家的所有回复!
bool GuessRight = false;
for(int i = 0; i<letters.Length; i++){
if(Guess == letters[i]){
Solution[i] = letters[i];
GuessRight = true;
}
} // this was the right place to close it, not after the 'Lives--'
if(!GuessRight){
Lives--;
}