We're almost done. Why don't we make things easy for our soon-to-be users? We can imagine that there are certain dice that are popular in many games. Why not define some ready-made dice that people can use moving forward?
We're going to instantiate some dice in our class, and assign them to something called a 'Constant'. Constants are like variables, except they are unchanging - once they are assigned, they are assigned to that value - forever! They can't ever be changed. Note: You may have noticed that class names start with an uppercase - that is because class names are, in fact, constants!
We're going to assign some of these dice to constants to make it easier to use later.
Type this in the file roller.rb:SIX_SIDED_DIE = Die.new(6)
EIGHT_SIDED_DIE = Die.new(8)
TEN_SIDED_DIE = Die.new(10)
TWENTY_SIDED_DIE = Die.new(20)
So now, our file looks like this:
Type this in the file roller.rb:class Die
def initialize(sides)
@sides = sides
end
def generate_die_roll
rand(@sides) + 1
end
def roll(number=1)
roll_array = []
number.times do
roll_array << generate_die_roll
end
total = 0
roll_array.each do |roll|
new_total = total + roll
total = new_total
end
total
end
end
SIX_SIDED_DIE = Die.new(6)
EIGHT_SIDED_DIE = Die.new(8)
TEN_SIDED_DIE = Die.new(10)
TWENTY_SIDED_DIE = Die.new(20)
puts "We're rolling a six sided die!"
puts SIX_SIDED_DIE.roll
puts "Now we're rolling two 20 sided die twice!"
puts TWENTY_SIDED_DIE.roll(2)
And now you have a program that works, is readable, and easy to use. Congratulations!
Lets have some fun. launch irb and type the following:
Type this in irb:require './roller.rb'
This loads the file into irb, which lets us play with it. Try using the dice. Roll a few! Use the constants to roll dice that you have already defined, or create some new dice and test the bounds of the system.