Skip to content

Commit

Permalink
feat: Implement tilesets
Browse files Browse the repository at this point in the history
  • Loading branch information
kfischer-okarin committed Feb 17, 2023
1 parent 4818a1e commit 4482b2f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/dragon_skeleton/tilemap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,33 @@ class Tilemap
attr_accessor :x, :y
attr_reader :grid_w, :grid_h, :cell_w, :cell_h

def initialize(x:, y:, cell_w:, cell_h:, grid_w:, grid_h:)
def initialize(x:, y:, cell_w:, cell_h:, grid_w:, grid_h:, tileset: nil)
@x = x
@y = y
@cell_w = cell_w
@cell_h = cell_h
@grid_h = grid_h
@grid_w = grid_w
@tileset = tileset
@cells = grid_h.times.flat_map { |grid_y|
grid_w.times.map { |grid_x|
[
grid_x * cell_w,
grid_y * cell_h,
nil, # path
nil, nil, nil, nil, # r, g, b, a
nil, nil, nil, nil # tile_x, tile_y, tile_w, tile_h
].tap { |cell| cell.extend(Cell) }
nil, nil, nil, nil, # tile_x, tile_y, tile_w, tile_h
nil # tile
].tap { |cell|
cell.extend(Cell)
if tileset
cell.assign(tileset.default_tile)
cell.define_singleton_method(:tile=) do |tile|
assign(tileset[tile])
self[Cell.property_index(:tile)] = tile
end
end
}
}
}
@primitive = RenderedPrimitive.new(@cells, self)
Expand Down Expand Up @@ -58,7 +69,7 @@ def self.property_index(name)
@property_indexes[name]
end

array_accessors :x, :y, :path, :r, :g, :b, :a, :tile_x, :tile_y, :tile_w, :tile_h
array_accessors :x, :y, :path, :r, :g, :b, :a, :tile_x, :tile_y, :tile_w, :tile_h, :tile

def assign(values)
values.each do |name, value|
Expand Down
22 changes: 22 additions & 0 deletions tests/lib/dragon_skeleton/tilemap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ def test_tilemap_render(args, assert)
# rubocop:enable all
end

def test_tilemap_tileset(_args, assert)
tileset = Object.new
tileset.define_singleton_method(:default_tile) do
{ tile_w: 50, tile_h: 50 }
end
tileset.define_singleton_method(:[]) do |tile|
{ tile_x: 100, tile_y: 100 } if tile == :grass
end

tilemap = Tilemap.new(x: 50, y: 50, cell_w: 100, cell_h: 100, grid_w: 2, grid_h: 3, tileset: tileset)

assert.nil! tilemap[0, 0].tile_x
assert.nil! tilemap[0, 0].tile_y
assert.equal! tilemap[0, 0].tile_w, 50
assert.equal! tilemap[0, 0].tile_h, 50

tilemap[0, 0].tile = :grass

assert.equal! tilemap[0, 0].tile_x, 100
assert.equal! tilemap[0, 0].tile_y, 100
end

class Spy
attr_reader :calls

Expand Down

0 comments on commit 4482b2f

Please sign in to comment.