samedi 18 mai 2019

Random class and if statements in dice roll simulator?

I am a beginner at C# and I have a homework assignment where I have to write a dice roll simulator.

The user can chose a maximum of 5 die and then as they roll each one the sum is added up with the one rolled previously. At the end the number of rolls and the the total sum is presented.

However, if the user rolls a 6 then this result is not added to the sum but the die is rolled twice more and then the sum is added.

I have a few points where I have gotten stuck and/or would like to know a better way of writing it. I have included a snippet below.

  1. Below I have stated my Random class every time the dice rolls but is it possible for me to do this only once and then use throughout my code?

  2. Is there a simple way to write the part with what happens if you roll a 6? I mean I guess I could write another if statement every time the die rolls but seems that this would very long?

    if (intnumberofdie == 1)

        {
            Random rnd1 = new Random();
            int dice1 = rnd1.Next(1, 7);
    
            Console.WriteLine("You have rolled " + dice1);
    
    
        else if (intnumberofdie == 2)
    
        {
            Random rnd1 = new Random();
            int dice1 = rnd1.Next(1, 7);
    
            Console.WriteLine("The first die rolled " + dice1);
    
            Console.ReadKey();
    
            Random rnd2 = new Random();
            int dice2 = rnd2.Next(1, 7);
    
            Console.WriteLine("The second die has rolled " + (dice2));
    
            Console.ReadKey();
    
            Console.WriteLine("The total sum so far is " + (dice1 + dice2));
    
    

}




Aucun commentaire:

Enregistrer un commentaire