如何使用List.Contains

时间:2019-07-11 15:03:34

标签: c#

我已经分配了一些方法来制作Hangman游戏,到目前为止一切都还好,直到我意识到当我用char输入的单词有两个连续字符时,if语句无法得到以下内容

if (correctGuesses.Count == randomWord.Length)
{
    Console.WriteLine("You won the word is: {0}", randomWord);
    break;
}

因此,如果单词像Green一样,我将永远无法完成游戏 我正在尝试使用List.Contains('*')如果包含它,则在不中断的情况下继续运行并编写Word从而获胜,但是如果我输入'!',它将失败。在前面或者如果我不说的话,它会变成无尽的循环。如果有一种使用“包含”的方式,它不会只搜索一个符号,而是会检查每个符号,直到没有更多符号,请您帮我。 我将在此处发布代码。

static string GeneratingRandomWords()
{
    Random r = new Random();

    List<string> words = new List<string>() { /*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green" };
    string word = words[r.Next(0, words.Count)];
    return word;
}

static char Input()
{
    char inputt = char.Parse(Console.ReadLine());
    return inputt;
}

static char[] TransformingCharToInvisible(string randomWord)
{
    char[] charFromString = randomWord.ToCharArray();
    for (int i = 0; i < randomWord.Length; i++)
    {
        charFromString[i] = '*';
    }

    Console.WriteLine(charFromString);

    return charFromString;
}

static int CorrectGuesses(char input, string randomWord, int correct)
{
    if (randomWord.Contains(input))
    {
        Console.WriteLine("Next");
        correct++;
    }

    return correct;
}

static int Lives(string randomWord, char input, int lives)
{
    if (!randomWord.Contains(input))
    {
        Console.WriteLine("Try another one");
        lives--;
    }

    return lives;
}

static List<char> CorrectWord(List<char> correctGuesses, string randomWord, char input)
{
    if (randomWord.Contains(input))
    {
        correctGuesses.Add(input);

        char[] charFromString = randomWord.ToCharArray();
        for (int i = 0; i < randomWord.Length; i++)
        {
            charFromString[i] = '*';
            if (correctGuesses.Contains(randomWord[i]))
            {
                charFromString[i] = randomWord[i];
            }
        }

        Console.WriteLine(charFromString);
    }

    return correctGuesses;
}

static void Main(string[] args)
{
    string randomWord = GeneratingRandomWords();
    TransformingCharToInvisible(randomWord);
    List<char> correctGuesses = new List<char>();
    int lives = 10;
    int correct = 0;
    //bool won = true;

    while (true)
    {
        Console.WriteLine("Write a char");
        char input = Input();
        correct = CorrectGuesses(input, randomWord, correct);
        lives = Lives(randomWord, input, lives);
        if (correctGuesses.Contains(input))
        {
            Console.WriteLine("You've already tried '{0}', and it was correct!", input);
            continue;
        }

        correctGuesses = CorrectWord(correctGuesses, randomWord, input);

        if (lives == 0)
        {
            Console.WriteLine("You lose sorry, try againg next time ");
            break;
        }

        if (correctGuesses.Count == randomWord.Length)
        {
            Console.WriteLine("You won the word is: {0}", randomWord);
            break;
        }
    }         
}

2 个答案:

答案 0 :(得分:1)

这是您的代码的简化版本,其中我没有添加所有错误检查,但基础知识使用必需的Contains来检查是否找到字母

static void Main(string[] args)
{
    var lives = 10;
    var correctGuesses = new List<char>();

    var word = "green";

    while (true)
    {
        Console.WriteLine("Guess a letter? ");

        // deliberatly just check for 1 character for simplicity reasons
        var input = Console.ReadLine()[0];

        // if already guessed give a chance to the user to retry
        if (correctGuesses.Contains(input))
        {
            Console.WriteLine("Letter already guessed");
        }
        else
        {
            // if the word contains the letter
            if (word.Contains(input))
            {
                // add as a correct guess
                correctGuesses.Add(input);

                Console.WriteLine("Letter found");
            }
            else
            {
                // letter dont exist remove a life
                lives--;

                Console.WriteLine("Letter not found");
            }
        }

        // check if the user still have lives
        if (lives == 0)
        {
            Console.WriteLine("You lost");

            break;
        }
        // check if the amount of distinct character in the word match 
        // the amount found. This mean the word is completly guessed
        else if (word.Distinct().Count() == correctGuesses.Count())
        {
            Console.WriteLine("You won you found the word");

            break;
        }
    }

    Console.ReadKey();
}

答案 1 :(得分:0)

我不太了解你

但是我这样修改了您的代码:

    private static bool IsCorrectGuess(char input, string actualWord)
    {
        return actualWord.Contains(input);
    }


    private static void WriteCorrectGuesses(ICollection<char> correctGuesses, string randomWord)
    {
        char[] charFromString = randomWord.ToCharArray();
        for (var i = 0; i < randomWord.Length; i++)
        {
            charFromString[i] = '*';
            if (correctGuesses.Contains(randomWord[i]))
                charFromString[i] = randomWord[i];
        }

        Console.WriteLine(charFromString);
    }

    private static string GeneratingRandomWords()
    {
        var r = new Random();

        var words = new List<string>
        {
            /*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green"
        };
        return words[r.Next(0, words.Count)];
    }


    private static char Input()
    {
        return char.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
    }


    private static void Main(string[] args)
    {
        string randomWord = GeneratingRandomWords();

        var correctGuesses = new List<char>();
        WriteCorrectGuesses(correctGuesses, randomWord);

        var lives = 10;
        var correct = 0;
        //bool won = true;

        while (true)
        {
            Console.WriteLine("Write a char");
            char input = Input();

            if (IsCorrectGuess(input, randomWord))
            {
                // correct letter 

                int score = randomWord.ToCharArray().Count(item => item == input);

                for (var i = 0; i < score; i++)
                {
                    correctGuesses.Add(input);
                    correct++;
                }

                WriteCorrectGuesses(correctGuesses, randomWord);

                if (correctGuesses.Count == randomWord.Length)
                {
                    Console.WriteLine("You won the word is: {0}", randomWord);
                    Console.Read();
                    break;
                }

                Console.WriteLine("Next");
            }
            else
            {
                // wrong letter
                Console.WriteLine($"Try another one. You still have {lives} to try.");
                lives--;
            }

            if (lives == 0)
            {
                Console.WriteLine("You lose sorry, try again next time ");
                break;
            }
        }
    }