StringBuilder отображает пробелы в скрытом сообщении - PullRequest
0 голосов
/ 26 сентября 2018

Так что, по сути, я хочу, чтобы в переменной displayToPlayer автоматически добавлялись пробелы, но я не совсем уверен, как этого добиться.

Как я могу автоматически добавлять пробелы в скрытое сообщение, не используяповорот или он был добавлен к предполагаемому письму.

Текущий результат:

Current Result

Желаемый результат:

Desired Result

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace guessingGame
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] quoteList = {
                "NEVER GUNNA LET YOU DOWN",
                /*"NEVER GUNNA RUN AROUND",
                "THIS IS A TEST"*/
            };   // the list of quotes that need to be guessed by the player

            Random random = new Random((int)DateTime.Now.Ticks);
            string quoteToGuess = quoteList[random.Next(0, quoteList.Length)];
            string quoteToGuessUppercase = quoteToGuess.ToUpper();

            StringBuilder displayToPlayer = new StringBuilder(quoteToGuess.Length);
            for (int i = 0; i < quoteToGuess.Length; i++)
            {
                displayToPlayer.Append('*');
            }

            List<char> correctGuesses = new List<char>();
            List<char> incorrectGuesses = new List<char>();

            int quoteToGuessLength = quoteToGuess.Count(characters => !Char.IsWhiteSpace(characters));
            int turnsLeft = quoteToGuess.Distinct().Count(characters => !Char.IsWhiteSpace(characters)) + 3;
            bool quoteGuessed = false;
            int lettersRevealed = 0;

            string userInput;
            char userGuess;
            Console.WriteLine("Can you work out the quote? (you have {0} chances)", turnsLeft);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(displayToPlayer.ToString());
            Console.WriteLine();

            while (!quoteGuessed && turnsLeft > 0)
            {
                Console.Write("Enter your letter ==>");
                try
                {
                    userInput = Console.ReadLine().ToUpper();
                    userGuess = userInput[0];

                    if (correctGuesses.Contains(userGuess))
                    {
                        Console.WriteLine("You've already tried '{0}', and it was correct!", userGuess);
                        continue;
                    }
                    else if (incorrectGuesses.Contains(userGuess))
                    {
                        Console.WriteLine("You've already tried '{0}', and it was wrong!", userGuess);
                        continue;
                    }

                    if (quoteToGuessUppercase.Contains(userGuess))
                    {
                        correctGuesses.Add(userGuess);

                        for (int i = 0; i < quoteToGuess.Length; i++)
                        {
                            if (quoteToGuessUppercase[i] == userGuess)
                            {
                                displayToPlayer[i] = quoteToGuess[i];
                                lettersRevealed++;
                            }
                        }

                        if (lettersRevealed == quoteToGuess.Length)
                        {
                            quoteGuessed = true;
                        }

                        turnsLeft--;
                        Console.Clear();
                        Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
                        Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
                        Console.WriteLine();
                        Console.WriteLine(displayToPlayer.ToString());
                        Console.WriteLine();
                        Console.WriteLine("Correct guess, there's a '{0}' in it!", userGuess);
                        Console.WriteLine();

                    }
                    else
                    {
                        incorrectGuesses.Add(userGuess);
                        turnsLeft--;
                        Console.Clear();
                        Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
                        Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
                        Console.WriteLine();
                        Console.WriteLine(displayToPlayer.ToString());
                        Console.WriteLine();
                        Console.WriteLine("Incorrect guess, there's no '{0}' in it!", userGuess);
                        Console.WriteLine();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Enter A Valid Character");
                }
            }

            if (quoteGuessed)
            {
                Console.WriteLine(quoteToGuess);
                Console.WriteLine("You have guessed all {0} letters out of a total of {0} Well done!!!", quoteToGuessLength);
            }
            else
            {
                Console.WriteLine("You lost! It was '{0}'", quoteToGuess);
            }
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 26 сентября 2018

Вы можете полностью избавиться от StringBuilder и цикла for, используя System.Linq:

var displayToPlayer = new string(quoteToGuess.Select(c => c == ' ' ? ' ' : '*').ToArray());

Если вы получили сообщение об ошибке, потому что Select(), похоже, не определено, добавьте это сверху вашего файла:

using System.Linq;
0 голосов
/ 26 сентября 2018

Если я правильно вас понимаю, это, вероятно, сработает

for (int i = 0; i < quoteToGuess.Length; i++)
{
    displayToPlayer.Append(quoteToGuess[i] == ' ' ? ' ' : '*');
}

По сути, это говорит о том, что если символ с индексом i в quoteToGuess равен ' ', тогда добавьте ' ', если не добавить, '*'


?: Оператор (C # Reference)

Условный оператор (? :), обычно известный кактроичный условный оператор, возвращает одно из двух значений в зависимости от значения логического выражения.Ниже приводится синтаксис для условного оператора.

Строки и индексы

Индекс - это позиция объекта Char (не символа Unicode) в строкеИндекс - это неотрицательное число, начинающееся с нуля, начинающееся с первой позиции в строке, которая является нулевой позицией индекса

...