Keeping track of what the user inputs

2019-09-21 18:58发布

This is my hangman code, and its almost good up to the point where it displays the guessed letters. It only displays the most recent guessed letter but I want it to continue on from whats left off. Such as if a person guess "A" and then "L" then Guessed letters are A, L. I tried using a for loop after "Guessed letters are" but then it gives me the output "A, A, A, A, A". What should I do to fix this problem?

class Hangman
{
    public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
    public string[] torture = new string[6] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
    public char[] guessed = new char[26];
    int i;

    public void randomizedWord()
    {

        Random random = new Random();

        int index = random.Next(0, 5);
        char[] hidden = new char[words[index].Length];
        string word = words[index];
        Console.WriteLine(words[index]);

        Console.Write("The word is: ");
        for (i = 0; i < hidden.Length; i++)
        {
            Console.Write('-');
            hidden[i] = '-';
        }
        Console.WriteLine();

        int lives = 6;
        do
        {
            Console.WriteLine("Guess a letter: ");
            char userinput = Console.ReadLine().ToCharArray()[0];
            index++;
            guessed[index] = userinput;
            Console.WriteLine("Guessed letters are: " + guessed[index]);

            bool foundLetter = false;
            for (int i = 0; i < hidden.Length; i++)
            {
                if (word[i] == userinput)
                {
                    hidden[i] = userinput;
                    foundLetter = true;
                    Console.WriteLine("You guessed right!");
                }
            }      
            for (int x = 0; x < hidden.Length; x++)
            {
                Console.Write(hidden[x]);
            }
            if (!foundLetter)
            {
                Console.WriteLine(" That is not a correct letter");
                lives--;

                if (lives == 5)
                {
                    Console.WriteLine("You lost a " + torture[0]);
                }
                else if (lives == 4)
                {
                    Console.WriteLine("You lost the " + torture[1]);
                }
                else if (lives == 3)
                {
                    Console.WriteLine("You lost your " + torture[2]);
                }
                else if (lives == 2)
                {
                    Console.WriteLine("You lost the " + torture[3]);
                }
                else if (lives == 1)
                {
                    Console.WriteLine("You lost your " + torture[4]);
                }
                else
                {
                    Console.WriteLine("You lost your " + torture[5]);
                    Console.WriteLine("You lose!");
                    break;
                }
            }

            bool founddash = false;
            for (int y = 0; y < hidden.Length; y++)
            {
                if (hidden[y] == '-')
                {
                    founddash = true;
                }
            }
            if (!founddash)
            {
                Console.WriteLine("  You Win!  ");
                break;
            }

            Console.WriteLine();
        } while (lives != 0);
    } 

标签: c# arrays char
2条回答
放我归山
2楼-- · 2019-09-21 19:25

The index variable is being set to a random number when the random word is selected in this line.

int index = random.Next(0, 5);

Then that index is being used to store the guesses in the do..while loop. However, since index starts from a random number between 0 and 5 you see unexpected behaviour.

Set index to 0 in the line before the do..while loop and the for loop (or the alternatives suggested elsewhere) should work e.g. as so

index = 0;
int lives = 6;
do
{
    // rest of the code
查看更多
祖国的老花朵
3楼-- · 2019-09-21 19:34

I was going to post on your other thread Hangman Array C#

Try changing this line

Console.WriteLine("Guessed letters are: " + guessed[index]);

To

Console.WriteLine("Guessed letters are: " + string.Join(" ", guessed).Trim());

I had a play with your hangman game and came up with this solution (while we are doing your homework). Although not related to the question.

public class HangCSharp
{
string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
List<char> guesses;
Random random = new Random();
string word = "";
string current = "";
int loss = 0;
readonly int maxGuess = 6;
int highScrore = 0;

public void Run()
{
    word = words[random.Next(0, words.Length)];
    current = new string('-', word.Length);
    loss = 0;
    guesses = new List<char>();
    while (loss < maxGuess)
    {
        Console.Clear();
        writeHeader();
        writeLoss();
        writeCurrent();
        var guess = Console.ReadKey().KeyChar.ToString().ToUpper()[0];
        while (!char.IsLetterOrDigit(guess))
        {

            Console.WriteLine("\nInvalid Guess.. Please enter a valid alpha numeric character.");
            Console.Write(":");
            guess = Console.ReadKey().KeyChar;
        }
        while (guesses.Contains(guess))
        {
            Console.WriteLine("\nYou have already guessed {0}. Please try again.", guess);
            Console.Write(":");
            guess = Console.ReadKey().KeyChar;
        }

        guesses.Add(guess);
        if (!isGuessCorrect(guess))
            loss++;
        else if (word == current)
            break;
    }
    Console.Clear();
    writeHeader();
    writeLoss();
    if (loss >= maxGuess)
        writeYouLoose();
    else
        doYouWin();
    Console.Write("Play again [Y\\N]?");

    while (true)
    {
        var cmd = (Console.ReadLine() ?? "").ToUpper()[0];
        if (cmd != 'Y' && cmd != 'N')
        {
            Console.WriteLine("Invalid Command. Type Y to start again or N to exit.");
            continue;
        }
        else if (cmd == 'Y')
            Run();
        break;
    }
}

bool isGuessCorrect(char guess)
{
    bool isGood = word.IndexOf(guess) > -1;
    List<char> newWord = new List<char>();
    for (int i = 0; i < word.Length; i++)
    {
        if (guess == word[i])
            newWord.Add(guess);
        else
            newWord.Add(current[i]);
    }
    current = string.Join("", newWord);
    return isGood;
}

void writeCurrent()
{
    Console.WriteLine("Enter a key below to guess the word.\nHint: {0}", current);
    if (guesses.Count > 0)
        Console.Write("Already guessed: {0}\n", string.Join(", ", this.guesses));
    Console.Write(":");
}

void writeHeader()
{
    Console.WriteLine("Hang-CSharp... v1.0\n\n");
    if (highScrore > 0)
        Console.WriteLine("High Score:{0}\n\n", highScrore);
}

void writeYouLoose()
{
    Console.WriteLine("\nSorry you have lost... The word was {0}.", word);
}

void doYouWin()
{
    Console.WriteLine("Congratulations you guessed the word {0}.", word);

    int score = maxGuess - loss;
    if (score > highScrore)
    {
        highScrore = score;
        Console.WriteLine("You beat your high score.. New High Score:{0}", score);
    }
    else
        Console.WriteLine("Your score:{0}\nHigh Score:{1}", score, highScrore);

}

void writeLoss()
{
    switch (loss)
    {
        case 1:
            Console.WriteLine(" C");
            break;
        case 2:
            Console.WriteLine(" C{0} #", Environment.NewLine);
            break;
        case 3:
            Console.WriteLine(" C\n/#");
            break;
        case 4:
            Console.WriteLine(" C\n/#\\");
            break;
        case 5:
            Console.WriteLine(" C\n/#\\\n/");
            break;
        case 6:
            Console.WriteLine(" C\n/#\\\n/ \\");
            break;
    }
    Console.WriteLine("\n\nLives Remaining {0}.\n", maxGuess - loss);
}
}

Can be run as new HangCSharp().Run();

查看更多
登录 后发表回答