简体   繁体   中英

Loto game in c#

I m trying to make some kind of game with c#, its loto game there is 10 columns. The computer has to generate 6 numbers to fill that 10 columns, my code is like:

public static int[] Get() 
    { 
        int[] a = new int[6];
        System.Random r = new System.Random();
        bool flag; int val; 
        for (int i = 0; i < a.Length; ++i)
        {
            flag = false; 
            do 
            { 
                val = r.Next(1, 50);
                for (int k = 0; k < i; ++k)     
                    if (a[k] == a[i])
                    { 
                        flag = true; 
                        break; 
                    } 
                a[i] = val; 
            } while (flag);  
        } 
        return a;
    }
    public static void Main()
    { 
        int[] a; 
        for (int i = 0; i < 10; ++i) 
        { 
            a = Get();
            foreach (int x in a)  
                Console.Write("{0} ", x);
            Console.WriteLine(); 
        } 
    }

but it gives result same, like

4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
4 44 19 44 22 7
22 29 28 15 33 6

so whats wrong at my code.
Thank you

The Random class is seeded from the system time.
When you make lots of Random s in a row, they will end up getting created at the same time and will use the same seed.

You should re-use the Random instance across calls to Get() .

Becouse of random class, its default method takes time from computer's current time so you are calling that method at same time and results are same. You can modify code as below

 public static int[] Get(System.Random r)
    {
        int[] a = new int[6];
        bool flag;
        int val;

        for (int i = 0; i < a.Length; ++i)
        {
            flag = false;

            do
            {
                val = r.Next(1, 50);
                for (int k = 0; k < i; ++k)
                    if (a[k] == a[i])
                    {
                        flag = true;
                        break;
                    }
                a[i] = val;
            } while (flag);
        }

        return a;
    }


    public static void Main()
    {
        int[] a;
        System.Random r = new System.Random();

        for (int i = 0; i < 10; ++i)
        {
            a = Get(r);

            foreach (int x in a)
                Console.Write("{0} ", x);
            Console.WriteLine();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM