Skip to content

Instantly share code, notes, and snippets.

@elinachar
Created May 9, 2018 16:16
Show Gist options
  • Save elinachar/34650491a3181be0d3447c7454ea7c0a to your computer and use it in GitHub Desktop.
Save elinachar/34650491a3181be0d3447c7454ea7c0a to your computer and use it in GitHub Desktop.
rock_paper_scissors
def round
# Get user's user_selection
puts 'Please type your selection "rock" [r], "paper" [p] or "scissors" [s]. You can always quit the game by typing "quit" [q].'
user_input = gets.chomp.downcase
# Create a list with the selections of the game (except the quit option)
options = ["rock", "paper", "scissors", "r", "p", "s"]
# Check if the user has selected to quit or if he has typed an invalid selection
if ["quit", "q"].include? user_input
puts "Happy to play with you! See you next time! Bye!!"
return false
elsif ! options.include? user_input
puts 'You typed an invalid selection.'
return true
end
# Get match of user's selection to the index of the options array
user_selection = options.index(user_input)
user_selection -= 3 if user_selection > 2
# Get a random computer's selection.
computer_selection = rand(3)
# Get the difference user_selection minus computer_selection
diff = user_selection - computer_selection
# Get the result of the game:
# 0 -> tie, -2, 1 -> win for the user, -1, 2 loss for the user
case diff
when 0
puts "You both selected #{options[computer_selection]}. There is a tie."
when -2, 1
puts "Congrats!! You won! The computer selected #{options[computer_selection]}."
when -1, 2
puts "Sorry but you lost... The computer selected #{options[computer_selection]}."
end
# Ask the user to continue playing
puts 'Would you like to play another round? Please type "yes" [y] or "no" [n]:'
newround = true
while newround
user_selection = gets.chomp.downcase
case user_selection
when "yes", "y"
return true
when "no", "n"
puts "Happy to play with you! See you next time! Bye!!"
return false
else
puts 'You typed an invalid selection. Please type in "yes" if you want to '\
'continue playing or "no" if you want to leave the game:'
end
end
end
# Welcome message and start the game
puts 'Hello! Ready to play "Rock, Paper, Scissors"?'
play = true
while play
play = round
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment