2014-01-30 26 views
0

我正在寫一個小猜謎遊戲。我正在寫點計算算法。有經驗的Ruby程序員如何重寫我的迷你遊戲?

我寫了下面的,它的工作原理。但是我覺得我正在將過程背景帶入Ruby,或者不正確地利用Ruby。

經驗豐富的Ruby程序員如何解決這個問題?您可以在TryRuby.com上測試代碼(在瀏覽器解釋器中複製和粘貼代碼)。

# g = guesses 
g = [{ id: 1, elmer­: 5, roger: 7, outcome: "Roger Win" },{ id: 2, elmer: 5, roger: 1, outcome: "Elmer Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }] 
# r = actual results 
r = [{ id: 1, elmer: 3, roger: 9, outcome: "Roger Win" },{ id: 2, elmer: 7, roger: 9, outcome: "Roger Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }] 
# points table 
p = []  
# rules: correct outcome = 1 point, perfect match = 5 points. 

# Loop over results. 
r.each do |result| 

    # Loop over guesses. 
    g.each do |guess| 

    # Make sure we compare corresponding ids. 
    # So, compare result 1 to guess 1, r2 to g2, etc.... 
    if result[:id] == guess[:id] 

     # Init a hash to store score 
     score = {} 

     # Did they guess the correct outcome? 
     if result[:outcome] == guess[:outcome] 

     # Correct outcome guessed! Make a score hash, give'em a point. 
     score[:id]  = result[:id] # game id 
     score[:points] = 1   # point 

     # Was it a perfect match? 
     if result[:elmer] == guess[:elmer] && result[:roger] == guess[:roger] 

      # Perfect match! Give them 4 points. 
      # They already got 1 point for guessing the correct outcome. 
      score[:points] += 4 
     end 
     end 

     # Add the score to the points table 
     p.push(score) unless score.empty? 
    end 
    end 
end 
+6

這個問題似乎是題外話題,因爲它是關於審查工作代碼。這些類型的問題可能適合http://codereview.stackexchange.com請在此發佈。 – CRABOLO

+1

我已經提出這個問題了。 –

回答

1

這對你來說看起來如何?

g.zip(r).collect do |guess, result| 
    points = (guess == result) ? 5 : guess[:outcome] == result[:outcome] ? 1 : 0 
    {:id => guess[:id], :points => points} 
end 

注意:這裏假定g和r按下列順序排列:id;如果沒有,你可以在排序之前做這個=) 此外,我會定義:FULL_SCORE = 5CORRECT_OUTCOME_SCORE = 1

+0

謝謝。你會考慮在Code Review上添加你的答案嗎? http://codereview.stackexchange.com/questions/40416/small-guessing-game-in-ruby –

+0

當然,完成=)。 – Abdo