Skip to content

Instantly share code, notes, and snippets.

@iodiot
Created December 22, 2015 16:36
Show Gist options
  • Save iodiot/c8ba445f6a37f2408889 to your computer and use it in GitHub Desktop.
Save iodiot/c8ba445f6a37f2408889 to your computer and use it in GitHub Desktop.
missile = {:cost => 53, :damage => 4}
shield = {:cost => 113, :armor => 7, :turns => 6}
drain = {:cost => 73, :damage => 2, :hit => 2, :turns => 1}
poison = {:cost => 173, :damage => 3, :turns => 6}
recharge = {:cost => 229, :mana => 101, :turns => 5}
spells = [missile, shield, poison, recharge]
spell_names = {missile => 'Magic Missile', drain => 'Drain', shield => 'Shield', poison => 'Poison', recharge => 'Recharge'}
min_mana_cost = 100500
min_attacks = []
100000.times do
player = {:hit => 50, :damage => 0, :armor => 0, :mana => 500, :spells => []}
boss = {:hit => 71, :damage => 10}
mana_cost = 0
turn = player
turns = {}
attacks = []
while boss[:hit] > 0 and player[:hit] > 0
boss[:hit] -= poison[:damage] if player[:spells].include? poison
player[:mana] += recharge[:mana] if player[:spells].include? recharge
player[:armor] = (player[:spells].include? shield) ? shield[:armor] : 0
player[:spells].each {|spell| turns[spell] -= 1}
player[:spells].select! {|spell| turns[spell] > 0}
if turn == player
# part 2
# player[:hit] -= 1
rest_spells = spells - player[:spells]
spell_to_cast = rest_spells.select {|spell| spell[:cost] <= player[:mana]}.sample
if spell_to_cast.nil?
player[:hit] = 0
break
end
player[:mana] -= spell_to_cast[:cost]
mana_cost += spell_to_cast[:cost]
attacks << spell_names[spell_to_cast]
if (spell_to_cast == missile) or (spell_to_cast == drain)
boss[:hit] -= spell_to_cast[:damage]
player[:hit] += drain[:hit] if spell_to_cast == drain
else
player[:spells] << spell_to_cast
turns[spell_to_cast] = spell_to_cast[:turns]
end
end
break if boss[:hit] <= 0
if turn == boss
player[:hit] -= boss[:damage] - player[:armor]
end
turn = (turn == player) ? boss : player
end
if (player[:hit] > 0) and (mana_cost < min_mana_cost)
min_mana_cost = mana_cost
min_attacks = attacks
#p mana_cost, attacks
end
end
p min_mana_cost, min_attacks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment