I wrote a "Rock, paper, scissors" game:
puts "Hello, this is a rock, papers, scissors game. Let's play."
puts "Player 1, plase enter your choice: \n"
puts "r for rock. \np for paper. \ns for scissors."
p1 = gets.chomp.downcase
puts "Player 2, please enter your choice: \n"
puts "r for rock. \np for paper. \ns for scissors."
p2 = gets.chomp.downcase
if p1 == 'r' && p2 == 's'
puts "Player 1 wins."
elsif p1 == 'r' && p2 == 'p'
puts "Player 2 wins."
elsif p1 == 'r' && p2 == 'r'
puts "Tie."
elsif p1 == 'p' && p2 == 'r'
puts "Player 1 wins."
elsif p1 == 'p' && p2 == 's'
puts "Player 2 wins."
elsif p1 == 'p' && p2 == 'p'
puts "Tie."
elsif p1 == 's' && p2 == 'r'
puts "Player 2 wins."
elsif p1 == 's' && p2 == 'p'
puts "Player 1 wins."
elsif p1 == 's' && p2 == 's'
puts "Tie."
end
It works, however, that's a lot of elsif
s, and I know that this is possible with case...when
statements, the thing is that I can't figure out how.
I was trying to use a return
statement depending on the input: "return 0 for rock, 1 for paper and 2 for scissors", and then use a conditional to say something like "hey, if player one returns 1 and player 2 also returns 1, then puts
'tie'", and the same for the other possible results.
I was trying to associate a number to the result: return - 1
when player one wins, return 0
for a tie, and return 2
for player two wins.
I did it like this, but it's kind of the same, and I feel that it's so bad:
case p1
when p1 == 'r' && p2 == 'r'
result = 0
when p1 == 'r' && p2 == 'p'
result = 1
when p1 == 'r' && p2 == 's'
result = -1
when p1 == 'p' && p2 == 'r'
result = -1
when p1 == 'p' && p2 == 'p'
result = 0
when p1 == 'p' && p2 == 's'
result = 1
when p1 == 's' && p2 == 'r'
result = 1
when p1 == 's' && p2 == 'p'
result = -1
when p1 == 's' && p2 == 's'
result = 0
end
if result == -1
puts "P1 wins"
elsif result == 0
puts "Tie"
elsif result == 1
puts "P2 wins"
end
I would appreciate any kind of help.