No Dice – 3 of 100 Days of Code
To get familiar with IntRanges, I built a small Dice Game app.
But if you’re expecting a full apk with a GUI, no dice. For more on this, watch the video at the bottom of the page.
While working on the Adding a Button Codelab, I picked up a few tricks for Kotlin. Remember all of those lottery examples you learned in your Intro to Programming classes? This time, instead of creating an array and selecting a random number, we have the IntRange datatype, and the random() method.
IntRange is, as the name suggests, used for storing a range of Integers. It’s like an array specific to Integers.
The random() method, when invoked upon an IntRange variable, randomly returns an integer from within the range.
To put this together, I created a small Kotlin terminal program which simulates die rolls. I created a Dice Class for instantiating Dice objects.
We all know dice have six sides. To reflect this in an IntRange, we’d store a range of values one to six (1..6). But for my program, I wanted to do change things up a bit.
In my version, I set the sides to range from 2 to 12 sides instead. This way it simulates the outcome of rolling two dice. (Minimum roll is 2, max is 12)
I included a method called roll(). This method simulates a dice roll. In this case, it returns a random number from 2 to 12.
For the final touch, I instantiated multiple Dice objects and output text to simulate multiple dice rolls by multiple players.
I had fun messing with the range operator. It looks like the next steps lead into building a dice simulator app. I’ll keep pushing forward and posting updates as I go along.
For more on this, watch the video below.
Join the mailing list to see updates like this every week!
Coding Fanatic