Tech Off Thread

15 posts

C# dice Roller

Back to Forum: Tech Off
  • User profile image
    St23aM

     

    I have posted this on my blog but, I thought I would post it here as well to see what advice / comments I can get. I appreciate your help and any advice that you might provide me about this program or programming in general. I am mainly using this program as a practice program for learning C#.  




    "I know I have asked this before and I have been working on this program for about 5 weeks now, However Could someone help me out again. All I want to do is return a String that has each die roll listed and then the total of those die rolls added together. This is the code I have I have changed it a bit please critique me I am trying to learn the right way to do things".  

    using System;

    namespace Dice

    {

       public class Dice

         {

          public string RollDice(int NumberOfDice, int NumberOfSides, int DiceMod)

          {

                      int Sides = NumberOfSides +1;

                      int X = 0;

                      int Roll = 0;

                      int[] Total = null;

                      Total = new int[NumberOfDice];

                      for (X = 0; X != NumberOfDice; X++)

                      {

                            Roll = 0;

                            Random DiceCall = new Random();

                            Roll += DiceCall.Next(1, Sides) + DiceMod;

                            Total[X] = Roll;

                           

                      }

                     

                      string[] ReturnString = (string[]) Total.Clone();

                      string ReturnWholeString = ReturnString.ToString();

                       return ReturnWholeString + Total;

               

                }

          }

    }

    Thanks ahead of time for the great responses and advice

    -St23aM

  • User profile image
    jj5

    How about something like this. You might like to play around with the formatting of the output.

    John.

      using System;
      using System.Text;

      public class EntryPoint {

        [STAThread]
        public static void Main(string[] args) {

          Console.WriteLine(Dice.Roll(2, 6));
          Console.Write("Press ENTER to exit.");
          Console.ReadLine();

        }
      }

      public class Dice {

        public static String Roll(Int32 numberOfDice, Int32 numberOfSides) {

          if (numberOfDice <= 0) {
            throw new ApplicationException("Number of die must be greater than zero.");
          }

          if (numberOfSides <= 0) {
            throw new ApplicationException("Number of sides must be greater than zero.");
          }

          Random rnd = new Random((Int32)DateTime.Now.Ticks);

          Int32[] roll = new Int32[numberOfDice];

          for (Int32 i = 0; i < numberOfDice; i++) {

            roll[i] = rnd.Next(1, numberOfSides);

          }

          StringBuilder result = new StringBuilder();
          Int32 total = 0;

          for (Int32 i = 0; i < roll.Length; i++) {

            total += roll[i];
            result.AppendFormat("Dice {0:00}:\t{1}\n", i + 1, roll[i]);

          }

          result.AppendFormat("\t\t--\n");
          result.AppendFormat("TOTAL:\t\t{0}\n", total);

          return result.ToString();

        }

      }

  • User profile image
    jj5

    Or, if you're not planning to eventually do something with that array, you could just do it this way. You could seed the random class with something more exotic (if you really care, if you're an online casino then you *really* care).

    John.

      using System;
      using System.Text;

      public class EntryPoint {

        [STAThread]
        public static void Main(string[] args) {

          Console.WriteLine(Dice.Roll(2, 6));
          Console.WriteLine(Dice.Roll(4,Eye Rolling);
          Console.Write("Press ENTER to exit.");
          Console.ReadLine();

        }
      }

      public class Dice {

        public static String Roll(Int32 numberOfDice, Int32 numberOfSides) {

          if (numberOfDice <= 0) {
            throw new ApplicationException("Number of die must be greater than zero.");
          }

          if (numberOfSides <= 0) {
            throw new ApplicationException("Number of sides must be greater than zero.");
          }

          Random rnd = new Random((Int32)DateTime.Now.Ticks);
          StringBuilder result = new StringBuilder();
          Int32 total = 0;

          for (Int32 i = 0; i < numberOfDice; i++) {

            Int32 roll = rnd.Next(1, numberOfSides);
            total += roll;
            result.AppendFormat("Dice {0:00}:\t{1}\n", i + 1, roll);

          }

          result.Append("\t\t--\n");
          result.AppendFormat("TOTAL:\t\t{0}\n", total);

          return result.ToString();

        }
      }

  • User profile image
    bwill

    I haven't tried your code, but the approach looks reasonable. 

    I'd move the "new Random()" call before the "for" loop; creating a new one every time is just wasting time.

    The string constructions at the end (with .Clone and casting to a string[]) seems a little wacky to me.  I'd just accumulate the dice roll string inside the for loop; on each loop add the current roll to the end of the string, and then tack the total on after the loop exits.

    There are a bunch of "coding style" things I'd do differently, but they don't effect functionality so I'll leave them alone.

    Let me know if memory size or program speed are important; for this application I assume they are not, if they are there are other things you can do to improve the code.  (Such as using StringBuilder as someone else suggested.)

  • User profile image
    St23aM

    yea the string constructions at the end were really just an experiment out of frustration HA! I do have a question also. You said "on each loop add the current roll to the end of the string, and then tack the total on after the loop exits" This is exactly what im trying to figure out how to do. Could you make a suggestion in code? I am sort of novice at programming, actualy somewhere between beginner and novice so I know what I want to do which is exactly what you said but, dont know how to express it in code. I guess my problem is I dont know enough about strings. Ill read up on them while I wait for your response. Thanks. Look forward to more replys.

  • User profile image
    St23aM

    Btw im trying to write this as component driven as possible. So that I can use this in alot of other tools with out having to recode a dice roller for each tool. So any advice on that as well would be great. Also thanks JJ5 im trying to soak in all of the great code you posted. Thank you.

  • User profile image
    Gambit

    I thought I was the only one liked making dice rolling programs Smiley

  • User profile image
    jj5

    St23aM wrote:
    You said "on each loop add the current roll to the end of the string, and then tack the total on after the loop exits" This is exactly what im trying to figure out how to do. Could you make a suggestion in code?


    This is pretty much what the code I posted does. I guess I should have commented it for you..

    This time with comments.

    John.

      using System;
      using System.Text;

      public class EntryPoint {

        [STAThread]
        public static void Main(string[] args) {

          // roll two die with 6 faces
          Console.WriteLine(Dice.Roll(2, 6));

          // roll 4 die with 8 faces
          Console.WriteLine(Dice.Roll(4,Eye Rolling);

          Console.Write("Press ENTER to exit.");
          Console.ReadLine();

        }
      }

      public class Dice {

        /// <summary>
        /// Rolls the specified number of die each with the specified number of
        /// sides and returns the result as a string, including the total.
        /// </summary>
        /// <param name="numberOfDice">The number of die to roll.</param>
        /// <param name="numberOfSides">The number of faces on each dice rolled.</param>
        /// <returns>A string containing the result of the roll.</returns>
        public static String Roll(Int32 numberOfDice, Int32 numberOfSides) {

          // don't allow a Number of Dice less than or equal to zero
          if (numberOfDice <= 0) {
            throw new ApplicationException("Number of die must be greater than zero.");
          }

          // don't allow a Number of Sides less than or equal to zero
          if (numberOfSides <= 0) {
            throw new ApplicationException("Number of sides must be greater than zero.");
          }

          // Create the random class used to generate random numbers.
          // See: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemRandomClassTopic.asp
          Random rnd = new Random((Int32)DateTime.Now.Ticks);

          // Create the string builder class used to build the string
          // we return with the result of the die rolls.
          // See: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextstringbuilderclasstopic.asp
          StringBuilder result = new StringBuilder();

          // Declare the integer in which we will keep the total of the rolls
          Int32 total = 0;

          // repeat once for each number of dice
          for (Int32 i = 0; i < numberOfDice; i++) {

            // Get a pseudo-random result for this roll
            Int32 roll = rnd.Next(1, numberOfSides);

            // Add the result of this roll to the total
            total += roll;

            // Add the result of this roll to the string builder
            result.AppendFormat("Dice {0:00}:\t{1}\n", i + 1, roll);

          }

          // Add a line to the result to seperate the rolls from the total
          result.Append("\t\t--\n");

          // Add the total to the result
          result.AppendFormat("TOTAL:\t\t{0}\n", total);

          // Now that we've finished building the result, get the string
          // that we've been building and return it.
          return result.ToString();

        }
      }

  • User profile image
    St23aM

    No gambit your not the only one Tongue Out Btw I think I saw yours while I was searching for Dice Rollers in C#. Not bad, no source code though. I am assuming it was the same Gambit anyways. jj5 im re-reading the code. I have another problem though, I have 3 parameters passed to my roll method one of them is Dice Mod .. it allows me to add a modifier to the die rolls. Its mainly for RPG stuff but, the problem I have is its getting added to each roll rather than to the total of the rolls.

  • User profile image
    spod

    so do any of you hardcore dice-roller guys use the crypto apis to get more-random pseudo-random numbers than Random() gives u Smiley

    just throwing out a sort of dice-roller challenge i suppose...

  • User profile image
    Gambit

    St23aM wrote:
    No gambit your not the only one Tongue Out Btw I think I saw yours while I was searching for Dice Rollers in C#. Not bad, no source code though. I am assuming it was the same Gambit anyways.


    If it was the The Gambit Site then it was me Smiley

    I don't usually put code up online(or any of my latest projects).

  • User profile image
    menu

    Hi i need help, the program should be work to rolls two dice (add the number on each die for the total), throw the dice 10 times, and show the result for each throw including display the highest and lowest number. so far i've done this (below) i don't know how to show the result and highest and lowest..please help or either of you guys have a better solution? thanks a lot

    class

    {

    Static void main (String[] args)

    {

     

    double raw;

    double big;

    double bigger;

    Int die;

    Random generator = new Random();

     

    Raw = generator. NextDouble();

    Console.WriteLine (“raw: {0}”, raw);

     

    big = raw * 6;

    Console.WriteLine (“bigger: {0}”, bigger);

     

    die = (int) big;

    Console.WriteLine(“die: {0}”, die);

     

    die = (int)(generator.NextDouble() * 6) + 1;

    Console.WriteLine(“another die: {0}”, die);

     

    Console.WriteLine();

    Console.WriteLine();

    Console.WriteLine(“please press enter key to quit”);

    Console.ReadLine();

    }//end main

    }//class

  • User profile image
    nightski

    BTW - It is currently throwing an ApplicationException.  I would recommend this be changed to an ArgumentException for obvious reasons.

  • User profile image
    brownsoft

    St23aM,
        I have done what you are trying to do in my RollDice.NET app that I wrote using C#.  If you check out the sandbox on Channel9, you can download my app which contains source. 
        My app is a more of specialty dice roller for different rpg systems such as storyteller,champions,D6 by West End Games and very generic diceroller.

    Matt

  • User profile image
    menu

    can you help me with my code? i past it down below thanks...

    the program should be work to rolls two dice (add the number on each die for the total), throw the dice 10 times, and show the result for each throw including display the highest and lowest number. so far i've done this (below) i don't know how to show the result and highest and lowest..please help or either of you guys have a better solution?

    class

    {

    Static void main (String[] args)

    {

    chemas-microsoft-comfficeffice" />> >

    double raw;

    double big;

    double bigger;

    Int die;

    Random generator = new Random();

    > >

    Raw = generator. NextDouble();

    Console.WriteLine (“raw: {0}”, raw);

    > >

    big = raw * 6;

    Console.WriteLine (“bigger: {0}”, bigger);

    > >

    die = (int) big;

    Console.WriteLine(“die: {0}”, die);

    > >

    die = (int)(generator.NextDouble() * 6) + 1;

    Console.WriteLine(“another die: {0}”, die);

    > >

    Console.WriteLine();

    Console.WriteLine();

    Console.WriteLine(“please press enter key to quit”);

    Console.ReadLine();

    }//end main

    }//class

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.