Skip to content

Instantly share code, notes, and snippets.

@jGRUBBS
Last active May 6, 2019 01:47
Show Gist options
  • Select an option

  • Save jGRUBBS/6468300 to your computer and use it in GitHub Desktop.

Select an option

Save jGRUBBS/6468300 to your computer and use it in GitHub Desktop.
Ruby Warrior
class Player
attr_accessor :warrior, :health, :direction
def play_turn(warrior)
@warrior = warrior
@turn ||= 0
check_direction
determine_action
@health = warrior.health
@turn = @turn + 1
end
def determine_action
if @turn == 0
@warrior.walk!
elsif is_wall?
@warrior.pivot!
elsif should_shoot?
warrior.shoot!
elsif warrior.feel(@direction).captive?
@warrior.rescue!(@direction)
elsif should_runaway?
runaway
elsif should_attack?
@warrior.attack!(@direction)
elsif needs_rest? && !under_attack?
@warrior.rest!
else
@warrior.walk!(@direction)
end
end
def should_attack?
@warrior.feel.enemy? || ( under_attack? && @warrior.feel.enemy? )
end
def under_attack?
(@health) ? @warrior.health < @health : false
end
def needs_rest?
@warrior.health < 20
end
def check_direction
@directions ||= [:forward, :backward]
@direction ||= :forward
end
def should_runaway?
( @warrior.health < 10 ) && under_attack?
end
def is_wall?
@warrior.feel(@direction).wall?
end
def should_shoot?
look_around
return !@warrior.feel.enemy? && (!@look_around[:forward].include?("captive") && @look_around[:forward].include?("enemy"))
end
def look_around
@look_around = {}
@directions.each do |direction|
@look_around[direction] = []
@warrior.look(direction).each do |space|
if space.captive?
@look_around[direction] << "captive"
elsif space.enemy?
@look_around[direction] << "enemy"
end
end
end
end
def runaway
(@look_around[:backward].include?("enemy")) ? @warrior.walk! : @warrior.walk!(:backward)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment