Home > Mobile >  Why does my code only work correctly if it runs into a breakpoint but not without it
Why does my code only work correctly if it runs into a breakpoint but not without it

Time:03-28

Hey I'm about to make a game in ASP.Net MVC and my problem is that my code adds the same object to my list 2 times when you run it without a breakpoint. But it works perfectly when you set a breakpoint anywhere. So can anyone help me with this issue please? I think it overrides something or that the code runs faster then it adds objects to the list but I don't know how to avoid these things yet.

        [HttpPost]
    public ActionResult StartView(WizardModel model)
    {
        model.Runde = 1;
        model.SpielerAnzahl = 2;

        int kartenImDeck = 60;

        for (int i = 0; i < model.SpielerAnzahl; i  )
        {
            if (model.SpielerListe[i].SpielerName == null)
            {
                int spielerZahl = i   1;

                model.SpielerListe[i].SpielerName = "Spieler "   spielerZahl;
            }
            List<WizardModel.Karten> kartenAufDerHand = new List<WizardModel.Karten>();

            Random rand = new Random();

            kartenAufDerHand = KartenAusteilen(kartenImDeck, model, rand);

            model.SpielerListe[i].KartenListe = kartenAufDerHand;
        }

        return View("GameView", model);
    }
public List<WizardModel.Karten> KartenAusteilen(int kartenImDeck, WizardModel model)

    {

        kartenImDeck = 60;

        var rand = new Random();
        List<int> listNumbers = new List<int>();
        int number;

        WizardModel.Karten karten = new WizardModel.Karten();
        List<WizardModel.Karten> kartenAufDerHand = new List<WizardModel.Karten>();

        for (int i = 0; i < model.Runde; i  )
        {
            number = rand.Next(1, 15);

            karten.KartenWert = number;

            string[] farben = { "rote", "blaue", "gruene", "gelbe" };

            int index = rand.Next(farben.Length);

            karten.KartenFarbe = farben[index];

            kartenImDeck--;

            if (number == 14)
            {
                karten.IstNarr = true;
            }
            if (number == 15)
            {
                karten.IstWizard = true;
            }
            //wizardModel.KartenListe.Add(karten);

            if (karten.IstNarr == true)
            {
                karten.BildPfad = "narr1.png";
            }
            else if (karten.IstWizard == true)
            {
                karten.BildPfad = "zauberer1.png";
            }
            else
            {
                karten.BildPfad = karten.KartenFarbe   karten.KartenWert.ToString()   ".png";
            }
        }
        kartenAufDerHand.Add(karten);

        return kartenAufDerHand;
    }

CodePudding user response:

Move the new Random() call outside of the for loop, random is seeded using time and calling new in a loop causes all the instances to use the same seed.

  • Related