猜游戏C#Enter

时间:2018-10-24 16:27:09

标签: c#

我有一个问题,如何设置条件,即如果用户在猜数字时按“ Enter”,程序将询问“ Enter a number”!

Program randomNumberA = new Program();
        int r = randomNumberA.RandomNumber();

do
{
    Console.WriteLine("Take a guess.\n");
    string n = userNumberA.UserNumber();
    int num;
    int.TryParse(n, out num);
    ConsoleKeyInfo key = Console.ReadKey();

    if (IsAllDigits(n))
    {
        if (num > r)
        {
            Console.WriteLine("Your guess is too high!\n");
            userGuess++;
        }
        if (num < r)
        {
            Console.WriteLine("Your guess is too low!\n");
            userGuess++;
        }
        if (num == r)
        {
            Console.WriteLine($"Good job, {name}! You guessed my number in {userGuess} guesses!");
            break;
        }
    }
    else if (!IsAllDigits(n) || string.IsNullOrEmpty(n) || !char.IsNumber(key.KeyChar))
    {
        Console.WriteLine("Please enter the correct number!");
        continue;
    }
} while (userGuess <= USER_LIMIT);

if (userGuess > USER_LIMIT)
{
    Console.WriteLine("Game Over!");
}

此逻辑检查游戏,但如果用户按下“ Enter”按钮仍然无法正常工作

1 个答案:

答案 0 :(得分:0)

您发布的代码有点不完整,但是您正在将userNumberA.UserNumber()r的结果进行比较,直到最后一个key条件都没有使用else if ,这很令人困惑。

我认为您的逻辑可以稍作更改。这是一个示例,其中包含一些硬编码的值,您应该可以在现有代码中利用这些值:

private static Random _random = new Random();

static void Main(string[] args)
{
    // Pick a random number between 1 and 100 for the user to guess
    int secretNumber = _random.Next(1, 101);

    int USER_LIMIT = 3;
    int userGuess = 0;

    Console.Write("Please enter your name: ");
    string name = Console.ReadLine();

    while (userGuess < USER_LIMIT)
    {
        userGuess++;
        Console.Write("Guess a number between 1 and 100: ");
        int num;

        if (int.TryParse(Console.ReadLine(), out num))
        {
            if (num > secretNumber)
            {
                Console.WriteLine("Your guess is too high!\n");
            }
            else if (num < secretNumber)
            {
                Console.WriteLine("Your guess is too low!\n");
            }
            else
            {
                Console.WriteLine($"\nGood job, {name}! That only took {userGuess} guesses!");
                break;
            }
        }
        else
        {
            Console.WriteLine("Please enter a valid number!");
        }
    }

    Console.WriteLine("\nGame Over!");
    if (userGuess == USER_LIMIT) Console.WriteLine($"\nThe number was: {secretNumber}");

    GetKeyFromUser("\nDone! Press any key to exit...");
}