John Carter John Carter - 2 months ago 9
Ruby Question

Ruby Method Always reset the number

I have this method here that basically counts player wins and computer wins.

def increment_winner(player, computer)

player_count = 0
computer_count = 0

if win?(player, computer)
player_count+=1
elsif win?(computer, player)
computer_count+=1
end

prompt("Player Count: #{player_count}")
prompt("Computer Count: #{computer_count}")

end


I tried to use to call it via:

increment_winner(choice, computer_choice)


But each time I call the game it always reset the number of counts to zero.

Here's my whole code:

WINNING_COMBO = {
'r' => ['sc', 'l'],
'p' => ['r', 'sp'],
'sc' => ['p', 'l'],
'l' => ['sp', 'p'],
'sp' => ['sc', 'r']
}

def win?(first, second)
WINNING_COMBO[first].include?(second)
end


def display_results(player, computer)
if win?(player, computer)
prompt("You won this round!")
elsif win?(computer, player)
prompt("Computer won this round! You loose!")
else
prompt("It's a tie on this round! No one wins!")
end
end

def increment_winner(player, computer)

player_count = 0
computer_count = 0

if win?(player, computer)
player_count+=1
elsif win?(computer, player)
computer_count+=1
end

prompt("Player Count: #{player_count}")
prompt("Computer Count: #{computer_count}")

end

loop do # main loop
choice = ''
loop do
prompt("Choose a key:")
VALID_CHOICES.each do |short_name, complete_name|
prompt("'#{short_name}' for #{complete_name}")
end
choice = Kernel.gets().chomp().downcase()

if VALID_CHOICES.include?(choice)
break
else
prompt("That's not a valid choice.")
end
end

computer_choice = VALID_CHOICES.keys.sample
display_results(choice, computer_choice)
increment_winner(choice, computer_choice)
prompt("Do you want to play again? ('yes' or 'no')")

loop do
answer = Kernel.gets().chomp()
if answer.casecmp('yes').zero?
break
elsif answer.casecmp('no').zero?
prompt("Thank you for playing!\n Have a nice day! Good bye!")
exit
else
prompt("Please enter either 'yes' or 'no'.")
end

end

end


Any idea how can I improve the method so it will not reset the count? If it's not possible, how can I use it within the loop? How can I know w/c variable to use to know which is the winner?

NOTE: I don't want to use instance or global variable here as it is for object oriented.

Answer

Just pass the initial values to the function:

def increment_winner(player, computer, counts)
    if win?(player, computer)
      counts[:player] += 1
    elsif win?(computer, player)
      counts[:computer] += 1
    end

    prompt("Player Count: #{counts[:player]}")
    prompt("Computer Count: #{counts[:computer]}")
end

and call this function with the hash param:

counts = {player: 0, computer: 0}
loop do # main loop
  ......
  increment_winner(choice, computer_choice, counts)
  ......
end