EXERCISE
Continue your craps program (starting code included).
When executed, this program should print out two random numbers, one on each line, simulating the roll of two dice.
If the numbers add up to 7 or 11, write a message that reads "YOU WIN!", if they add up to 2, 3, or 12, write a message that reads "YOU LOSE!", otherwise, write a message that reads "THE POINT IS {number}".
HINTS
Get a random number between 1 and 6 by doing:
rand(1..6)
Specify multiple conditions with || (OR) and && (AND):
if dinner == "tacos" || dinner == "pizza"
if dinner == "tacos" && dessert == "ice cream"
The included starting code from lab 1:
die1 = rand(1..6)
puts die1
die2 = rand(1..6)
puts die2
total = die1 + die2
puts "The total is #{total}"
Next we want to check if the total is equal to one of the winning numbers 7 or 11. If it is, display "YOU WIN!"
if total == 7 || total == 11
puts "YOU WIN!"
end
Note that you can't write total == 7 || 11
. Both sides of the OR (||
) operator need to be complete boolean expressions.
Now we want to add another conditional branch to our logic to check if the total is equal one of the craps numbers 2, 3, or 12. If it is, display "YOU LOSE!".
if total == 7 || total == 11
puts "YOU WIN!"
elsif total == 2 || total == 3 || total == 12
puts "YOU LOSE!"
end
Lastly, we need one more branch in the logic to account for all of the other possible conditions (i.e. if the total is not equal to 7, 11, 2, 3, or 12) and, in that situation, display the total as the point:
if total == 7 || total == 11
pus "YOU WIN!"
elsif total == 2 || total == 3 || total == 12
puts "YOU LOSE!"
else
puts "THE POINT IS #{total}"
end
The final code looks like:
die1 = rand(1..6)
puts die1
die2 = rand(1..6)
puts die2
total = die1 + die2
puts "The total is: #{total}"
if total == 7 || total == 11
puts "YOU WIN!"
elsif total == 2 || total == 3 || total == 12
puts "YOU LOSE!"
else
puts "THE POINT IS #{total}"
end