用 score_increments 重构网络游戏模型 (DRY)
Refacting Model (DRY) with score_increments for an internet game
我最近制作了一个在线游戏,想知道如何重构下面的代码以使其保持 DRY。任何帮助将不胜感激。
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
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
我最近制作了一个在线游戏,想知道如何重构下面的代码以使其保持 DRY。任何帮助将不胜感激。
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
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