C#再次玩数字游戏

时间:2019-11-30 13:55:45

标签: c# string

我正在尝试实现用户输入Y或N再次玩游戏或退出游戏的功能,但是我一直在努力设法避免大规模重写代码逻辑……我我今天才刚回到C#并是一个初学者,所以请对我轻松一点:)我已经准备好了userContinue字符串,只想输入一种简单的方法来重复游戏并添加保持得分的方法(慢慢来)改进游戏)

    using System;

namespace Guess_Number_V2
{
    class Program
    {
        static void Main(string[] args)
        {

            do
            {
                PlayGame();
                Console.WriteLine("Would you play to play again? Y or N");
            } while (Console.ReadLine().ToLower() == "y");

        }

        public static voic PlayGame()
        {
            Random rand = new Random();
            int randNum = rand.Next(1, 11);
            int incorrectGuesses = 0;
            int userScore = 10;
            int userGuess;
            int perGuess = 1;
            string userContinue;
            bool correctGuess = false;

            Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");

            userGuess = int.Parse(Console.ReadLine());

            while (correctGuess == false)
            {
                if (userGuess == randNum)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
                    correctGuess = true;
                }

                if (userGuess > randNum)
                {
                    userScore -= perGuess;
                    incorrectGuesses++;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wrong guess again, to high!");

                    correctGuess = false;
                }

                else if (userGuess < randNum)
                {
                    userScore -= perGuess;
                    incorrectGuesses++;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wrong guess again, to low!");

                    correctGuess = false;
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果将您的游戏逻辑放在自己的方法中,这将有所帮助。说FileInputStream fis = new FileInputStream(new File("filene.xlsx"));。然后,您可以简单地编写:

PlayGame()

此外,如果您进行“无限”循环并在猜测正确时使用static void Main(string[] args) { do { PlayGame(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Would you play to play again? Y or N"); } while (Console.ReadLine().ToLower() == "y"); } 中断循环,则可以简化逻辑。

您可以在每个循环的开头读取并解析用户输入。

设置用户分数错误的猜测次数,红色控制台颜色也只能执行一次。

经过测试的有效代码:

break;