Solution: Counting to 21
Go over the implementation of the game, counting to 21, which also performs user input validation and raises a runtime error if needed.
We'll cover the following...
Solution
puts("You and me take turns say a number, the player forced to say '21' loses. At each turn, player can increase the number 1 or 2.") print("Do you want to go first? (y/n) ") choice = gets.chomp the_number = 0 if choice == "y" print("You (1 or 2): ") player_number = gets.chomp.to_i if player_number > the_number && player_number <= (the_number + 2) the_number = player_number else raise "Foul! You lose." end end while the_number <= 20 # stategy my_next_number = my_next_number_1 = the_number + 1 my_next_number_2 = the_number + 2 if my_next_number_2 % 3 == 2 my_next_number = my_next_number_2 end puts(" Me: #{my_next_number}") the_number = my_next_number if the_number == 21 break elsif the_number == 20 print("You (#{the_number + 1} :-( ): ") else print("You (#{the_number + 1} or #{the_number + 2}): ") end player_number = gets.chomp.to_i if player_number > the_number && player_number <= (the_number + 2) the_number = player_number else raise "Foul! You lose." end end
Solution to game: Counting to 21
Note: To take the first turn, you must enter
y
(in lowercase) when prompted. ...