一个小型的彩票游戏项目和我遇到的挑战。 C #

A small lottery game project and challenges I have. C #

编辑:所有挑战均已完成。添加了最终代码。

在等待我的编程教育开始(.NET/C#)的同时,我也在练习自己。我还是一个 Padawan coder.

现在我正在编写一个小型彩票游戏,它应该像这样工作:

Correct lottery line: 7,8,9,10,11,12,15 
Additional numbers: 21,22,23,24
James: 1,4,6,7,8,20,21      2 correct, 1 additional number    
Jane: 1,6,8,12,14,15,35     3 correct, zero additional number*

下面添加了完整的代码:

    internal class Program
    {
        static List<Player> listOfPlayers = new List<Player>();
        static List<int> lotto35 = new List<int>();
        static List<int> lotto11 = new List<int>();
        static List<int> lotto7 = new List<int>();
        static List<int> lotto4 = new List<int>();
        static Random rnd = new Random();
        static string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\lottorad.txt";

        static void Header()
        {
            Console.WriteLine("\n*****************************************************************" +
            "\n*                                                               *" +
            "\n*\t\tWelcome to The Little Lottery Game\t\t*" +
            "\n*                                                               *" +
            "\n*****************************************************************");
        }
        static void LottoNumbers()
        {
            // Generate numbers 1-35 and add them to lotto35:
            for (int i = 1; i <= 35; i++)
                lotto35.Add(i); 

            // Generate 11 random numbers from lotto35. No duplicates allowed!:
            for (int i = 0; i < 11; i++)
            {
                // Gets a random number from lotto35 and stores it in "index":
                int index = rnd.Next(lotto35.Count);
                //Console.Write(lottoNumbers[index] + ", ");
                
                lotto11.Add(lotto35[index]);

                // Removes the last number retrieved from lotto35 to prevent duplicates:
                lotto35.RemoveAt(index);
            }
            //lotto11.Sort();

            //Console.ReadKey();
        }

        static void RunGame()
        {
            //Console.WriteLine(string.Join(", ", lotto11.GetRange(0, 11)));

            Console.Write("\nType in your Name or press ENTER to continue." +
                    "\nName: ");
            // Wait for name input:
            string nameInput = Console.ReadLine();

            if (!string.IsNullOrEmpty(nameInput))
            {
                int[] numberInput = new int[7];
                for (int i = 0; i < 7; i++)
                {
                    // Use this bool to keep looping until user input correct number:
                    bool moveon = false;
                    do
                    {
                        Console.Write($"Type in lotto nr {i + 1}: ");
                        string input = Console.ReadLine();

                        // First check if input is a number, next check that input is between 1 and 35.
                        // The function TryParse takes the string input and tries to parse it as an int.
                        // If it's parsed, it's returned as a new int 'useinput':

                        if (int.TryParse(input, out int useinput) && useinput >= 1 && useinput <= 35 && (!numberInput.Contains(useinput)))
                        {
                            // Add number to int[]:
                            numberInput[i] = useinput;
                            // Allow user to skip loop and enter new number.
                            // 'Continue' breaks directly out of loop:
                            moveon = true; continue;
                        }
                        else { Console.WriteLine($"Error: Only numbers between 1 and 35 and no duplicate:"); }
                    }
                    // Keep looping until moveon = true:
                    while (moveon == false);
                }

                // Sort every input in numberInput ascending:
                Array.Sort(numberInput);

                // Add name and sorted numbers to list of players:
                listOfPlayers.Add(new Player(nameInput, numberInput));
            }

            else if (string.IsNullOrEmpty(nameInput))
            {
                // Add numbers to lotto7 and lotto4 and sort them
                lotto7.AddRange(lotto11.GetRange(0, 7));
                lotto7.Sort();
                lotto4.AddRange(lotto11.GetRange(7, 4));
                lotto4.Sort();
                lotto11.Sort();

                Console.Clear();
                Header();
                
                // Output the result
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("\nLottery numbers: " + string.Join(", ", lotto7));
                Console.WriteLine("Additional numbers: " + string.Join(", ", lotto4));

                // List players and their lottery numbers:
                foreach (Player player in listOfPlayers)
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("{0} {1}", player.Name + ", Your numbers: ", string.Join(", ", player.Numbers));

                    // Save result in lottorad.txt
                    using (StreamWriter outputFile = new StreamWriter(path, true))
                    {
                        outputFile.WriteLine(DateTime.Now);
                        outputFile.WriteLine("{0} {1}", player.Name + ", Your numbers: ", string.Join(", ", player.Numbers));
                    }

                    // Check how many correct numbers each player have
                    int count1 = 0;
                    int count2 = 0;
                    for (int i = 0; i < player.Numbers.Length; i++)
                    {
                        if (lotto7.Contains(player.Numbers[i]))
                            count1++;
                        if (lotto4.Contains(player.Numbers[i]))
                            count2++;
                    }

                    Console.Write("You have ");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(count1);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.Write(" correct lottery numbers plus ");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(count2);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.Write(" additional numbers.");
                    Console.WriteLine();

                }
                // Ask player to quit or play again
                bool moveon = false;
                do
                {
                    Console.ResetColor();
                    Console.Write("\nTo quit press Q : To play again press ENTER : ");
                    string letter = Console.ReadLine();
                    letter = letter.ToUpper();
                    
                    if ( letter == "Q")
                    {
                        Console.WriteLine("Thanks for playing!");
                        Environment.Exit(0);
                    }
                    else
                    {
                        // Clear all data before new game starts
                        Console.Clear();
                        Console.ResetColor();
                        listOfPlayers.Clear();
                        lotto35.Clear();
                        lotto11.Clear();
                        lotto7.Clear();
                        lotto4.Clear();
                        Header();
                        moveon = true; continue;
                    }
                    
                }
                while (moveon == false);
                
            }

            // Start over again.
            LottoNumbers();
            RunGame();
        }

        static void Main(string[] args)
        {

            Header();
            LottoNumbers();
            RunGame();
        }

        public class Player
        {
            public string Name { get; set; }
            public int[] Numbers { get; set; }
            public Player(string name, int[] numbers)
            {
                Name = name;
                Numbers = numbers;
            }
        }
    }
}

当您将 numberInput 数组赋给 Player 变量时

here: listOfPlayers.Add(new Player(nameInput, numberInput));

你实际上引用了同一个数组。所以基本上,你所有的玩家都在内存中引用同一个数组。

您要做的是为每个玩家注册该数组的副本。

您可以使用 .Clone() 轻松完成复制并转换回 int[] :

//old code
listOfPlayers.Add(new Player(nameInput, numberInput));`
//new code
listOfPlayers.Add(new Player(nameInput, (int[])numberInput.Clone()));`

您需要将 numberInput 移动到循环中,如下面的代码所示。

作为奖励,我确实应用了您即将推出的一些功能来提供一些帮助:)

internal class Program
{
    static List<Player> listOfPlayers = new List<Player>();

    static void RunGame()
    {
        Console.Write("Type in your name or press ENTER to continue." +
                "\nName: ");
        // Wait for name input:
        string nameInput = Console.ReadLine();

        if (!string.IsNullOrEmpty(nameInput))
        {
            int[] numberInput = new int[7];
            for (int i = 0; i < 7; i++)
            {
                // Use this bool to keep looping until user input correct number:
                bool moveon = false;
                do
                {
                    Console.Write($"Type in lotto nr {i + 1}: ");
                    string input = Console.ReadLine();

                    // First check if input is a number, next check that input is between 1 and 35.
                    // The function TryParse takes the string input and tries to parse it as an int.
                    // If it's parsed, it's returned as a new int 'useinput':
                    if (int.TryParse(input, out int useinput) && useinput >= 1 && useinput <= 35)
                    {
                        // Add number to int[]:
                        numberInput[i] = useinput;
                        // Allow user to skip loop and enter new number.
                        // 'Continue' breaks directly out of loop:
                        moveon = true; continue;
                    }
                    else { Console.WriteLine($"Error: Input a number between 1 and 35:"); }
                }
                // Keep looping until moveon = true:
                while (moveon == false);
            }

            // Sort every input in numberInput ascending:
            Array.Sort(numberInput);

            // Add name and sorted numbers to list of players:
            listOfPlayers.Add(new Player(nameInput, numberInput));
        }

        else
        {
            // List players and their lottery numbers:
            foreach (Player player in listOfPlayers)
            {
                Console.WriteLine("{0} {1}", player.Name, string.Join(", ", player.Numbers));
            }
        }


        // Start over again.
        RunGame();
    }

    static void Main(string[] args) { RunGame(); }

    public class Player
    {
        public string Name { get; set; }
        public int[] Numbers { get; set; }
        public Player(string name, int[] numbers)
        {
            Name = name;
            Numbers = numbers;
        }
    }
}
}