Skip to content

connermcd's beginner code

connermcd edited this page Mar 13, 2013 · 1 revision
class Player
  def initialize
    @dir = :backward
    @retreating = false
    @health_last_turn = 20
    @hit_wall = false
  end

  def play_turn(warrior)
    @warrior = warrior
    @space = warrior.feel(@dir)
    handle_turn
    @retreating = !(@health_last_turn == warrior.health)
    @health_last_turn = warrior.health
  end

  def handle_turn
    @space.empty? ? handle_empty : handle_object
  end

  def handle_empty
    if taking_damage?
      low_on_health? && !@retreating ? retreat! : @warrior.shoot!(@dir)
    elsif enemies_ahead?
      @warrior.shoot!(@dir)
    else
      handle_safety
    end
  end

  def handle_object
    case
      when @space.captive? then handle_captive
      when @space.wall? then handle_wall
      when @space.enemy? then handle_enemy
    end
  end

  def handle_captive
    @warrior.rescue!(@dir)
    if !@hit_wall
      reverse_direction
    end
  end

  def handle_wall
    @hit_wall = true
    reverse_direction
    handle_safety
  end

  def handle_safety
    full_health? ? @warrior.walk!(@dir) : @warrior.rest!
  end

  def handle_enemy
    low_on_health? ? retreat! : @warrior.attack!(@dir)
  end

  def reverse_direction
    @dir = @dir == :forward ? :backward : :forward
  end

  def retreat!
    @retreating = true
    reverse_direction
    @warrior.walk!(@dir)
  end

  def full_health?
    @warrior.health == 20
  end

  def low_on_health?
    @warrior.health < 12
  end

  def taking_damage?
    @health_last_turn > @warrior.health
  end

  def enemies_ahead?
    look = @warrior.look(@dir)
    look[1].enemy? || (look[2].enemy? && !look[1].captive?)
  end

end