public
Description: ruby-warrior AI inspired by roboticist Rodney Brooks
Homepage:
Clone URL: git://github.com/akkartik/brooks-ruby-warrior.git
Kartik K. Agaram (author)
Mon Mar 09 18:10:31 -0700 2009
100644 83 lines (70 sloc) 1.777 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Player
  def initialize()
    @max_health = nil
    @prev_health = nil
    @warrior = nil
    @direction = :forward
    @health_history = []
    @direction_history = []
  end
 
  def play_turn(warrior)
    @max_health ||= warrior.health
 
    @warrior = warrior
    updateHistory
 
#? return rescue! if captive_nearby?
    return walk! if feel.stairs?
    return rest! if needRest && !beingShotAt
    return attack! unless feel.empty?
#? find_empty_direction
 
    reverse_direction if walking_into_fire
    walk!
  end
 
  def needRest
    @warrior.health < @max_health
  end
 
  def beingShotAt
    @warrior.health < @prev_health
  end
 
  def updateHistory
    @prev_health = @curr_health
    @curr_health = @warrior.health
    @health_history << @curr_health
    @direction = @warrior.direction_of_stairs
#? @direction_history << @direction
  end
 
  def walk!
    @warrior.walk! @direction
  end
  def attack!
    @warrior.attack! @direction
  end
  def rescue!
    @warrior.rescue! @direction
  end
  def rest!
    @warrior.rest!
  end
  def feel
    @warrior.feel @direction
  end
 
  def captive_nearby?
    [:forward, :left, :right, :backward].each do |dir|
      return @direction = dir if @warrior.feel(dir).captive?
    end
  end
 
  def find_empty_direction
    [:forward, :left, :right, :backward].each do |dir|
      return @direction = dir if @warrior.feel(dir).empty?
    end
  end
 
  def walking_into_fire
    return false if @direction_history[-1] != @direction_history[-2] ||
        @direction_history[-2] != @direction_history[-3]
    @health_history[-1] < @health_history[-2] && @health_history[-2] < @health_history[-3]
  rescue
    false
  end
 
  def reverse_direction
    @direction = (@direction == :forward) ? :backward : :forward
  end
end