Skip to content
Montell Tome edited this page Apr 28, 2014 · 2 revisions
class Player 
   
  def initialize 
    @max_health = 20
    @health = @max_health
    @direction = :forward
  end 
  
  def play_turn(warrior)
    @direction = :backward if captive_behind?(warrior)
    if warrior.look(@direction).empty? 
      warrior.walk!(@direction)  
    else
      if warrior.feel(@direction).empty?
        if under_attack?(warrior)  
          warrior.walk!(@direction)
        else
          if see_enemy?(warrior)
            captive_before_enemy?(warrior) ? warrior.walk!(@direction) : warrior.shoot!(@direction)  
          else
            dying?(warrior) ? warrior.rest! : warrior.walk!(@direction)     
          end
        end
      else
        if warrior.feel(@direction).enemy?
          warrior.attack!(@direction) 
        elsif warrior.feel(@direction).captive?
          warrior.rescue!(@direction)
        else 
          turn_around?(warrior) 
        end
      end
    end
    @health = warrior.health  
  end
  
  def hurt?(warrior)
    warrior.health < @max_health  
  end
  
  def under_attack?(warrior)
    @health > warrior.health   
  end 
  
  def dying?(warrior)
    warrior.health <= 9
  end
  
  def turn_around?(warrior)
    @direction = @direction == :backward ? :forward : :backward    
    warrior.pivot!(@direction)
  end

  def see_enemy?(warrior)
    warrior.look(@direction).any? {|space| space.enemy?}
  end

  def see_captive?(warrior)
    warrior.look(@direction).any? {|space| space.captive?}
  end

  def captive_before_enemy?(warrior)
    enemy_position = captive_position = -1
    warrior.look(@direction).each_with_index do |space, index|
      if space.enemy?
        enemy_position = index  
      elsif space.captive? 
        captive_position = index  
      end
    end  
    captive_position != -1 && captive_position <= enemy_position
  end
  
  def captive_behind?(warrior)
    warrior.look(:backward).any? {|space| space.captive?}  
  end
end