class ModernWarfare2 < Challenge
GAME_MODES = ['Capture the Flag', 'Demolition', 'Domination', 'Headquarters', 'Sabotage', 'Search and Destroy']
MAP_PACK_0 = ['Afghan', 'Derail', 'Estate', 'Favela', 'Highrise', 'Invasion', 'Karachi', 'Quarry', 'Rundown', 'Scrapyard', 'Skidrow', 'Sub Base', 'Terminal', 'Underpass', 'Wasteland']
MAP_PACK_1 = ['Bailout', 'Salvage', 'Storm', 'Crash', 'Overgrown']
MAP_PACK_2 = ['Carnival', 'Fuel', 'Strike', 'Trailer Park', 'Vacant']
attr_accessor :map_pack_0, :map_pack_1, :map_pack_2
field :maps_and_modes, :type => Array
def set_maps_and_modes
result = []
maps = []
maps << MAP_PACK_0 if self.map_pack_0
maps << MAP_PACK_1 if self.map_pack_1
maps << MAP_PACK_2 if self.map_pack_2
maps.flatten.sort_by{rand}[0..4].map do |map|
result << "#{map} - #{GAME_MODES.sort_by{rand}.first}"
end
self.maps_and_modes = result
end
end
Refactorings
No refactoring yet !
Rymaï
August 10, 2010, August 10, 2010 20:17, permalink
Hey,
I quickly ended up with this solution, inject is cool! ;)
class ModernWarfare2 < Challenge
GAME_MODES = ['Capture the Flag', 'Demolition', 'Domination', 'Headquarters', 'Sabotage', 'Search and Destroy']
MAP_PACK_0 = ['Afghan', 'Derail', 'Estate', 'Favela', 'Highrise', 'Invasion', 'Karachi', 'Quarry', 'Rundown', 'Scrapyard', 'Skidrow', 'Sub Base', 'Terminal', 'Underpass', 'Wasteland']
MAP_PACK_1 = ['Bailout', 'Salvage', 'Storm', 'Crash', 'Overgrown']
MAP_PACK_2 = ['Carnival', 'Fuel', 'Strike', 'Trailer Park', 'Vacant']
attr_accessor :maps_and_modes, :map_pack_0, :map_pack_1, :map_pack_2
field :maps_and_modes, :type => Array
def set_maps_and_modes
maps = (0..2).inject([]) { |memo, i| memo + (self.send(:"map_pack_#{i}") ? self.class.const_get("MAP_PACK_#{i}") : []) }
self.maps_and_modes = maps.sort_by{ rand }[0..4].inject([]) { |memo, map| memo << "#{map} - #{GAME_MODES.choice}" }
end
end
I've removed the code that is out of the scope for this refactoring, but you can find it at http://github.com/teddyzetterlund/challenger/ if you want.
The result that I get on "maps_and_modes" is => ['Map name - Game mode', 'Map name - Game mode', .etc] but it feels like it could be written in a cleaner way.