我这里有这种方法,基本上算上玩家获胜和计算机胜利。
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
我试图通过以下方式来调用它:
increment_winner(choice, computer_choice)
但每次我打电话给游戏时,它总是将计数数重置为零。
这是我的全部代码:
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
知道如何改进方法,以免重置计数?如果不可能,我怎么能在循环中使用它?我怎么知道使用w / c变量来知道哪个是赢家?
注意:我不想在这里使用实例或全局变量,因为它是面向对象的。
答案 0 :(得分:0)
您只需将create global variables移动到全局范围并在其前面添加$
:
$player_count = 0
$computer_count = 0
def increment_winner(player, computer)
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
但是,全局变量都被忽略了,所以你可以改为静态本地化:
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
这可能是类似Ruby的解决方案,虽然我从你的编辑中看到你不想要这个解决方案!
答案 1 :(得分:0)
只需将初始值传递给函数:
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
并使用散列参数调用此函数:
counts = {player: 0, computer: 0}
loop do # main loop
......
increment_winner(choice, computer_choice, counts)
......
end