Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Abstraction FTW

  • Loading branch information...
commit 03daf986dcbb77a16706cfff798d1c5075acf525 1 parent 3122e4f
Gabe Berke-Williams authored September 23, 2010

Showing 1 changed file with 36 additions and 8 deletions. Show diff stats Hide diff stats

  1. 44  player.rb
44  player.rb
... ...
@@ -1,26 +1,28 @@
1 1
 class Player
2 2
   MAX_HEALTH = 20
  3
+  # When we have less than this % health, rest (unless we're not in a safe
  4
+  # space)
  5
+  MINIMUM_PERCENT_HEALTH = 70
3 6
   def play_turn(warrior)
4  
-    current_health = warrior.health
  7
+    @warrior = warrior
5 8
     @previous_health ||= current_health
6  
-    percent_health = (current_health.to_f / MAX_HEALTH) * 100
7 9
     taking_damage = (current_health < @previous_health)
8 10
     space = warrior.feel
9 11
     if space.stairs?
10 12
       warrior.walk!
  13
+    elsif space.captive?
  14
+      warrior.rescue!
  15
+    elsif space.enemy?
  16
+      warrior.attack!
11 17
     elsif space.empty?
12  
-      # warrior might be attacked even if space ahead is empty
13  
-      # So if we're low on health and not taking damage, rest a bit.
14  
-      if percent_health < 60 and not taking_damage and not space.stairs?
  18
+      if should_rest?
15 19
         # Regain some health
16 20
         warrior.rest!
17 21
       else
18 22
         warrior.walk!
19 23
       end
20 24
     else
21  
-      if space.enemy?
22  
-        warrior.attack!
23  
-      end
  25
+      puts "Weird space: #{space.inspect}"
24 26
     end
25 27
     # available methods for a Space (returned by warrior.feel)
26 28
     # stairs?
@@ -35,4 +37,30 @@ def play_turn(warrior)
35 37
     # Set @previous_health for next turn
36 38
     @previous_health = current_health
37 39
   end
  40
+
  41
+  # Is this space safe to rest in?
  42
+  def in_safe_space?
  43
+    space = @warrior.feel
  44
+    (space.empty? or space.captive? or space.wall?)
  45
+  end
  46
+
  47
+  # Should the warrior rest?
  48
+  def should_rest?
  49
+    in_safe_space? and low_on_health? and
  50
+      not taking_damage? and # Not in danger
  51
+      not @warrior.feel.stairs? # No need to rest when we're about to clear the level
  52
+  end
  53
+
  54
+  def current_health
  55
+    @warrior.health
  56
+  end
  57
+
  58
+  def taking_damage?
  59
+    taking_damage = (current_health < @previous_health)
  60
+  end
  61
+
  62
+  def low_on_health?
  63
+    percent_health = (current_health.to_f / MAX_HEALTH) * 100
  64
+    percent_health < MINIMUM_PERCENT_HEALTH
  65
+  end
38 66
 end

0 notes on commit 03daf98

Please sign in to comment.
Something went wrong with that request. Please try again.