I’m trying to write a program that simulates the dice game bones. The idea is to roll five dice and get the lowest score possible–threes have a value of 0. Once the five dice are rolled the player/bot MUST select at least one die (or more) from the five and roll the rest. This is what’s posing a problem to me. If there’s no threes then the “keeper” array which I push the dice the bot keeps to ends up being empty, which necessitates an embedded loop. Since I’m pretty new to coding I really can’t figure out a way to create an embedded loop that will ensure that at least one dice is designated as a keeper. For your sanity’s sake I’ll say that the “beta” version of this program I’ll present now is intended to do the following: Create a bot that tries to get the lowest score on one round of bones. Ie. The dice are rolled once. Then he tries to pick the lowest score possible. If there are no threes (equivalent to 0) he picks ones. The problem I’m trying to solve is creating an embedded loop that ensures at least one die is selected for the keeper array. The code is mainly to demonstrate how ugly my solution is and give an idea for a better solution.
#rolls dice
srand
dice = []
5.times do
dice.push(rand(6)+1)
end
puts dice
puts " "
#initialize keeper and roll again arrays
i = 0
keeper = []
roll_again = []
#select any 3s from the dice roll and put them in keeper
dice.each do |d|
if d == 3
keeper.push(d)
else
i +=1 #dummy operation to keep if statement functioning, tragically ugly code
end
end
#in the case that no threes were rolled, ones are selected
if keeper.length == 0
dice.each do |f|
if f == 1
keeper.push(f)
else
i+= 1
end
end
else
i += 1
end
puts "Keeper:"
puts keeper
puts "Roll Again:"
puts roll_again
For a beginner you are doing fine 🙂 I’ll just show you some things that can help you with this exercise, you learn best by trying out different things and trying to understand them.
Another thing you can do is group the dice array:
That way you can instantly see if the array for a given number is empty or not. Note that it’s easy to do array differences in Ruby, which might help you with removing dice:
In fact array intersection also is a good way to see if a certain element is part of an array:
Some more tips: You don’t need dummy statements for your
elsebranches, you can just leave them out. I also strongly recommend going through the docs ofArrayandEnumerable, there’s lot of useful methods in there.