2014-09-11 112 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