2014-09-11 36 views
1

我正在用红宝石为我的第一个程序创建一个摇滚,剪刀,纸程序。红宝石:Rock Scissors Paper program。如何使算法功能正常?

我正在考虑使用名为@wins的散列来确定某个组合是否获胜。如果双手相同,则结果为Draw!。否则,结果是Lose!

我努力实现算法来判断结果。如何检查给定的组合是否存在于@wins散列中以判断它是赢或现在?

class Hand 
    attr_accessor :shape 
    @@shapes = [:rock, :scissors, :paper] 
    def generate 
     @shape = @@shapes[rand(3)] 
    end 
end 

class Game 
    @wins = {rock: :scissors, scissors: :paper, paper: :rock} 
    def judge(p1, p2) 
     'Win!' if (a way to see if a given combination exists within a @wins hash)   # Not working 
     'Draw!' if p1 == p2 # Not working 
     else 'Lose!' 
    end 
end 

player_hand = Hand.new 
player_hand.shape = ARGV.join.to_sym 
puts player_hand.shape # Debug 

computer_hand = Hand.new 
computer_hand.shape = computer_hand.generate 
puts computer_hand.shape # Debug 

game = Game.new 
puts game.judge(player_hand.shape, computer_hand.shape) 

回答

0
def judge(p1, p2) 
    case 
    when @wins[p1] == p2 then "Win" 
    when @wins[p2] == p1 then "Lose" 
    else "Draw" 
    end 
end 
+0

13:在'法官 ':未定义的方法'[]' 为零:NilClass(NoMethodError) 从29:在'

“' – 2014-09-11 08:17:15

+0

啊,右。 '@wins = ...'应该在'initialize'方法中;你现在拥有它的方式,它在课堂上设置,“判断”看不到它。甚至更好(更好),使它成为一个常量('WINS = ...'),在这种情况下它保持正确的位置(没有'initialize')。 – Amadan 2014-09-11 08:18:06

+0

得到它的工作。谢谢! – 2014-09-11 09:20:33