Hey I am new to ruby and I have sat for a long time trying to find out what I've done wrong in this code, there isn't any error but it isn't giving me my desired output as a normal game of rock paper scissors. Here is my code:
puts "Rock, Paper or Scissors"
choice = gets.chomp
cchoice = ["Rock", "Paper","Scissors"]
comp = rand(1..3)
won = false
puts "Computer chose #{cchoice[comp]}"
if (choice == "Rock")
if (comp == 2)
won = false
end
if (comp == 3)
won = true
end
elsif (choice == "Paper")
if (comp == 3)
won = false
end
if (comp == 1)
won = true
end
elsif (choice == "Scissors")
if (comp == 1)
won = false
end
if (comp == 2)
won = true
end
else
puts "I dont know what that means so-"
end
if (won)
puts "YOU WON!!!"
else
puts "You lost.."
end
Thanks for any help!
The rules of rock, paper, scissors can be expressed as a simple hash:
conditions = {
"Rock" => "Scissors",
"Paper" => "Rock",
"Scissors" => "Paper"
}
So you can simply check if one player won over the other with:
if conditions[player_1] == player_2
puts "Player one wins!"
elsif player_1 == player_2
puts "Its a draw!"
else
puts "Player two wins!"
end
This is far less complex then a tree of nested if/else statements.
conditions = {
"Rock": "Scissors",
"Paper": "Rock",
"Scissors": "Paper"
}
puts "Rock, Paper or Scissors"
choice = gets.chomp.capitalize
cchoice = conditions.keys.sample
puts "Computer chose #{ cchoice }"
if conditions[choice] == cchoice
puts "You won!"
elsif cchoice == choice
puts "Its a draw."
elsif conditions[cchoice] == choice
puts "You lost."
else
puts "#{choice} is not a valid option"
end
This covers the four potential outcomes which are:
Also instead of rand you can use Array#sample to select a random element from the keys of the hash which avoids the need to use array indices.
Your random number generator generates numbers between 1-3, it should be between 0-2 since you are trying to index a list
comp = rand(0..2)
Also change the comparison in the if clause to reflect the above change,
Another thing you might have forgot is the draw condition (if both select the same thing)