mikeyfz6 - 1 year ago 90
Ruby Question

# Increment variables within a method?

I'm trying to build a rock, paper, scissors game. Could someone please tell me or point me in the right direction of where I'm going wrong with this code?

I want the

`players_score`
and
`cpu_score`
variables to increment by
`1`
each time either one wins a round.

``````choice = ["rock", "paper", "Scissors"]

players_score = 0
cpu_score = 0

def win_lose(a,b,c,d)

if a == "rock" && b == "scissors"
c+=1
puts "YOU WIN!!"

elsif a == "scissors" && b == "rock"
d+=1
puts "YOU LOSE!!"

elsif a =="paper" && b == "rock"
c+=1
puts "YOU WIN!!"

elsif a =="rock" && b == "paper"
d+=1
puts "YOU LOSE!!"

elsif a == "scissors" && b == "paper"
c+=1
puts "YOU WIN!!"

elsif a == "paper" && b == "scissors"
d+=1
puts "YOU LOSE!!"

else a == b
puts "Its a Draw this time!!"
end

end

while players_score < 2 && cpu_score < 2

print "Lets play. Plese choose rock, paper or scissors: "
players = gets.chomp.downcase
puts "You have #{players}"

cpu = choice.sample.downcase
puts "Computer has #{cpu}"

win_lose(players, cpu, players_score, cpu_score)
puts "scores are player #{players_score} , cpu #{cpu_score}"
end
``````

Return a value from `win_lose`, and use that to determine increment the variable, e.g.:

``````def win_lose(a,b,c,d)
if a == "rock" && b == "scissors"
c+=1
winner = 'player'
elsif a == "scissors" && b == "rock"
d+=1
winner = 'computer'
# [.. etc ..]
else a == b
winner = 'draw'
end

return winner
end

player_score = 0
cpu_score = 0
choice = ["rock", "paper", "Scissors"]

while players_score < 2 && cpu_score < 2
print "Lets play. Plese choose rock, paper or scissors: "
players = gets.chomp.downcase
puts "You have #{players}"

cpu = choice.sample.downcase
puts "Computer has #{cpu}"

winner = win_lose(players, cpu, players_score, cpu_score)
if winner == 'player'
player_score += 1
puts "YOU WIN!!"
elsif winner == 'computer'
cpu_score += 1
puts "YOU LOSE!!"
else
puts "It's a draw"
end

puts "scores are player #{players_score} , cpu #{cpu_score}"
end
``````

As you can see, this also allows you to now repeat the same "YOU WIN!!" sentence. I moved that outside the `win_lose` function so that this function does only one thing: determine the winner or loses, rather than two things: determine the winner or loser, and inform them of this.

This distinction is perhaps not important for such a small program, but as your programs grow it will be critical to keep your program understandable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download