Simple, Quality, Awesome Software

Dice Notation

Required Knowledge Before Starting

  • Using the Random class (Chapter 17).
  • Parsing user input (Chapter 8).
  • Making classes and properties (Chapter 18 and 19) are not required, but will probably be helpful.

Problem Description

In RPGs and other games, you frequently roll different types of dice and add the values up. These games have developed a system of notating what kinds of dice should be rolled in specific situations, including the number of sides of dice, the number to roll, and an additive offset.

For example, 3d6 is a shorthand way of saying, “roll 3 6-sided dice and add up the result.” 3d6+1 means, “roll 3 6-sided dice, add up the result, then add 1 to it.” In cases where only one die is rolled, the first number is optional, so “d20” means, “roll a single 20-sided die.”

Create a program that will allow the user to enter a string in this notation, parse it, simulate the specified roll, and output an integer result to the user.

Notation Meaning
1d6 Roll 1 6-sided die.
d6 Roll 1 6-sided die.
2d12 Roll 2 12-sided dice.
d20+1 Roll 1 20-sided die and add 1 to the result.
2d20-5 Roll 2 20-sided dice and subtract 5 from the result.

You can assume that entering multiple types of dice in a single line is not allowed (“2d20 + 2d4” is not legal).

Notes

The following might be helpful to you as you work on this problem:

Pay attention to how you call the Random.Next(int) method. To get values between 1 and 6, you must add 1 to Random.Next(6) because the Next method produces values between 0 and 1 less than the supplied value.

Some string methods might help you parse the input more gracefully:

  • "a b c".Split(' ') will produce an array of strings split from the input string ( ["a", "b", "c"]).
  • IndexOf('D') will return the index of the first occurrence of the 'D' character.
  • "a b c".Substring(2, 1) will return a new string starting at index 2 (remember it is 0-based indexing) of length 1, or in this case, "b".

Optional Features

  • Handling bad input is a bonus feature. To pass the project, valid input must produce correct results. Invalid input can crash the program and still pass. But it is a good bonus if you can safely handle invalid input and display a message to the user indicating so.
  • Looping to allow the user to enter multiple dice notations is not required, but a nice feature.
  • Handling spaces anywhere within the input is a nice plus.

Solution

DiceNotation.zip