用网络游戏的score_increments重构模型(DRY)

时间:2015-01-02 21:40:20

标签: ruby-on-rails ruby-on-rails-4

我最近建立了一个在线游戏,并想知道如何重构下面的代码以保持干燥。任何帮助将不胜感激。

before_create :game_score

def game_score
   level_one_a(kills)
   level_one_b(kills)
end

def self.level_one_a(kills)
    if kills >= 600
        increment!(:score, by = 6)
    elseif kills >= 500
        increment!(:score, by = 5)
    elseif kills >= 400
        increment!(:score, by = 4)
    end
end

def self.level_one_b(kills)
    if kills >= 550
        increment!(:score, by = 6)
    elseif kills >= 390
        increment!(:score, by = 5)
    elseif kills >= 348
        increment!(:score, by = 4)
    elseif kills >= 234
        increment!(:score, by = 3)
    end
end

1 个答案:

答案 0 :(得分:0)

LEVEL_ONE_KILLS_INCREMENT = {
                             :a => {600 => 6, 500 => 5, 400 => 4},
                             :b => {550 => 6, 390 => 5, 348 => 4, 234 => 3}
                            }

def self.level_one(kills, type)
  LEVEL_ONE_KILLS_INCREMENT[type].keys.each do |key|
     increment!(:score, by = LEVEL_ONE_KILLS_INCREMENT[type][key]) if kills >= key
  end
end