class BoardGame::Map
._. A simple board / map of tiles | 0123 X | ============================= | 0.… | Example 4X2 map, | 1..#. | with a piece | Y | placed in (2, 1) ‘———’
Attributes
height[R]
tiles[R]
width[R]
Public Class Methods
new(height, width)
click to toggle source
# File lib/boardgame/map.rb, line 11 def initialize(height, width) @height, @width = height, width validate_height initialize_map_tiles end
Public Instance Methods
[](x, y)
click to toggle source
Retrieves a tile for a given X/Y coord.
# File lib/boardgame/map.rb, line 18 def [](x, y) return @tiles[x][y] if within? x, y end
[]=(x, y, tile)
click to toggle source
Sets a tile for a given X/Y coord.
# File lib/boardgame/map.rb, line 23 def []=(x, y, tile) validate_coords(x, y) raise 'needs to be a tile' unless tile.is_a? BoardGame::Tile @tiles[x][y] = tile.move_to(x, y, self) end
as_json(*args)
click to toggle source
# File lib/boardgame/map.rb, line 45 def as_json(*args) tiles.as_json end
inspect()
click to toggle source
# File lib/boardgame/map.rb, line 34 def inspect buffer = "\n" 0.upto(max_y) do |ht| 0.upto(max_x) do |wd| buffer += self[wd, ht].inspect end buffer += "\n" end return buffer end
within?(x, y)
click to toggle source
Determine if x and y values are within the limits of the map.
# File lib/boardgame/map.rb, line 30 def within?(x, y) (x >= 0) && (x < height) && (y >= 0) && (y < height) end
Private Instance Methods
initialize_map_tiles()
click to toggle source
# File lib/boardgame/map.rb, line 51 def initialize_map_tiles @tiles = [] 0.upto(max_x) do |wd| @tiles[wd] = [] 0.upto(max_y) do |ht| self[wd, ht] = BoardGame::Tile.new({}) end end end
max_x()
click to toggle source
# File lib/boardgame/map.rb, line 61 def max_x width - 1 end
max_y()
click to toggle source
# File lib/boardgame/map.rb, line 65 def max_y height - 1 end
validate_coords(x, y)
click to toggle source
# File lib/boardgame/map.rb, line 69 def validate_coords(x, y) raise "Coords out of range for #{height}x#{width} map." unless within? x, y end
validate_height()
click to toggle source
# File lib/boardgame/map.rb, line 73 def validate_height unless height.is_a?(Fixnum) && width.is_a?(Fixnum) raise 'Expected height and width to be Fixnums' end end