Skip to content

Instantly share code, notes, and snippets.

@bvandgrift
Created March 7, 2014 02:46
Show Gist options
  • Save bvandgrift/9404286 to your computer and use it in GitHub Desktop.
Save bvandgrift/9404286 to your computer and use it in GitHub Desktop.
1st pass solution to bloc.io/ruby_warrior/9
class Player
MAX_HEALTH = 20
DYING_HEALTH = 10
def me
@game[:me]
end
def found_wall?
@game[:found_wall]
end
def find_wall
@game[:found_wall] = (me.feel.wall? || me.feel(:backward).wall?)
end
def search
unless found_wall?
find_wall || me.walk!(:backward)
end
end
def nearby_enemy?
me.feel.enemy? || me.feel(:backward).enemy?
end
def enemies_in_line_of_sight
enemies = []
[:forward, :backward].each do |dir|
me.look(dir).each_with_index do |s, idx|
break if s.captive?
next unless s.enemy?
enemy = {}
enemy[:direction] = dir
enemy[:distance] = idx
enemy[:shoots?] = true if shooter?(s.unit)
enemies << enemy
end
end
enemies
end
def enemy_in_sights?
! @game[:enemies].empty?
end
def captive_nearby?
me.feel.captive? || me.feel(:backward).captive?
end
def debug(thing)
raise thing.inspect.to_s
end
def play_turn(warrior)
tick(warrior)
free_captive ||
retreat ||
rest ||
fight ||
shoot ||
move
end
def shooter?(unit)
unit.abilities.has_key? :shoot!
end
def move
me.feel.wall? ? me.pivot! : me.walk!
end
def fight
me.attack! if nearby_enemy?
end
def shoot
if enemy_in_sights?
enemies = @game[:enemies].sort { |a,b| a[:distance] <=> b[:distance] }
enemy = find_target(enemies)
if enemy
me.shoot!(enemy[:direction])
else
me.shoot!(enemies.first[:direction])
end
end
end
def find_target(enemy_list)
enemy = enemy_list.first
return enemy if enemy[:shoots?]
return find_target(enemy_list[1..-1]) if enemy_list.count > 1
nil
end
def retreat
me.walk!(:backward) if dying? && taking_damage?
end
def rest
return if taking_damage? || !hurt?
me.rest!
end
def free_captive
me.rescue! if me.feel.captive?
# me.rescue!(:backward) if me.feel(:backward).captive?
end
def current_health
@game[:health].last
end
def hurt?
current_health < MAX_HEALTH
end
def dying?
current_health < DYING_HEALTH
end
def taking_damage?
@game[:health].last < @game[:health][-2]
end
def tick(warrior)
@game ||= {}
@game[:me] = warrior
@game[:health] ||= [20]
@game[:health] << me.health
@game[:enemies] = enemies_in_line_of_sight
end
end
@bvandgrift
Copy link
Author

So this is pretty ugly; considering playing the full ruby-warrior, but my fear is that if I do that, I'll start writing games, and I don't need another hobby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment