Class: StackWars::Battlefield
- Inherits:
-
Object
- Object
- StackWars::Battlefield
- Defined in:
- lib/stack_wars/battlefield.rb
Constant Summary collapse
- SIZE =
9
- WHITE_BASELINE =
0
- BLACK_BASELINE =
SIZE - 1
Class Method Summary collapse
Instance Method Summary collapse
- #[](x, y) ⇒ Object
- #adjacent?(pos1, pos2) ⇒ Boolean
- #deployed_armies(player) ⇒ Object
-
#initialize(territories = nil) ⇒ Battlefield
constructor
A new instance of Battlefield.
-
#inspect ⇒ Object
loses instance variables, but better than hitting to_s() by default.
- #to_a ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(territories = nil) ⇒ Battlefield
Returns a new instance of Battlefield.
25 26 27 28 29 30 31 32 |
# File 'lib/stack_wars/battlefield.rb', line 25 def initialize(territories=nil) if territories @territories = territories else @territories = SIZE.times.map { |y| SIZE.times.map { |x| Territory.new([x,y]) } } end end |
Class Method Details
.from_json(json_file) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/stack_wars/battlefield.rb', line 7 def self.from_json(json_file) territory_data = JSON.parse(File.read(json_file)) territories = territory_data.map.with_index do |row, y| row.map.with_index do |t, x| occupant, strength = t if occupant == "unclaimed" Territory.new([x,y]) else Territory.new([x,y], :occupant => occupant, :army_strength => strength) end end end new(territories) end |
Instance Method Details
#[](x, y) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/stack_wars/battlefield.rb', line 34 def[](x,y) unless [x,y].all? { |c| (WHITE_BASELINE..BLACK_BASELINE).include?(c) } raise Errors::OutOfBounds end @territories[y][x] end |
#adjacent?(pos1, pos2) ⇒ Boolean
42 43 44 45 |
# File 'lib/stack_wars/battlefield.rb', line 42 def adjacent?(pos1, pos2) (pos1.row == pos2.row && (pos1.column - pos2.column).abs == 1) || (pos2.column == pos2.column && (pos1.row - pos2.row).abs == 1) end |
#deployed_armies(player) ⇒ Object
47 48 49 50 51 52 |
# File 'lib/stack_wars/battlefield.rb', line 47 def deployed_armies(player) # FIXME: Inefficient, can probably store integer values on write @territories.flatten.reduce(0) do |s, t| s + (t.occupant == player.color ? t.army_strength : 0) end end |
#inspect ⇒ Object
loses instance variables, but better than hitting to_s() by default
55 |
# File 'lib/stack_wars/battlefield.rb', line 55 alias_method :inspect, :to_s |
#to_a ⇒ Object
61 62 63 |
# File 'lib/stack_wars/battlefield.rb', line 61 def to_a Marshal.load(Marshal.dump(@territories)) end |
#to_s ⇒ Object
57 58 59 |
# File 'lib/stack_wars/battlefield.rb', line 57 def to_s TextDisplay.new(to_a).to_s end |