Class: Tilemap

Inherits:
Object
  • Object
show all
Defined in:
lib/fantasy/tilemap.rb

Constant Summary collapse

@@maps =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(map_name:, tiles:, tile_size: nil, tile_width: nil, tile_height: nil) ⇒ Tilemap

Returns a new instance of Tilemap.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/fantasy/tilemap.rb', line 6

def initialize(map_name:, tiles:, tile_size: nil, tile_width: nil, tile_height: nil)
  @tile_width = tile_width || tile_size
  @tile_height = tile_height || tile_size

  if @tile_height.nil? || @tile_width.nil?
    raise("Tile size is not properly defined. Either you set a `tile_size` or a `tile_width` and `tile_height`")
  end

  @map_name = map_name
  @tiles = tiles
  @position = Coordinates.zero

  @grid = Tilemap.load_grid(@map_name)
end

Instance Attribute Details

#positionObject

Returns the value of attribute position.



4
5
6
# File 'lib/fantasy/tilemap.rb', line 4

def position
  @position
end

Class Method Details

.base_pathObject



86
87
88
# File 'lib/fantasy/tilemap.rb', line 86

def base_path
  "#{Dir.pwd}/maps"
end

.load_grid(map_name) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/fantasy/tilemap.rb', line 64

def load_grid(map_name)
  File.readlines(Tilemap.locate_map(map_name), chomp: true).map do |line|
    line.each_char.map do |char|
      char == " " ? nil : char.to_i
    end
  end
end

.locate_map(map_name) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/fantasy/tilemap.rb', line 72

def locate_map(map_name)
  return @@maps[map_name] if @@maps[map_name]

  puts "Initialize map: '#{map_name}'"

  file_name = Dir.entries(base_path).find { |e| e =~ /^#{map_name}($|\.)/ }

  raise "Map file not found with name '#{map_name}' in #{base_path}" if file_name.nil?

  @@maps[map_name] = "#{base_path}/#{file_name}"

  @@maps[map_name]
end

Instance Method Details

#heightObject



25
26
27
# File 'lib/fantasy/tilemap.rb', line 25

def height
  @grid.length * @tile_height
end

#spawnObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fantasy/tilemap.rb', line 29

def spawn
  tile_position = Coordinates.zero

  @grid.each do |line|
    tile_position.x = 0

    line.each do |tile_index|
      unless tile_index.nil?
        render_tile(tile_index, tile_position)
      end

      tile_position.x += 1
    end

    tile_position.y += 1
  end
end

#widthObject



21
22
23
# File 'lib/fantasy/tilemap.rb', line 21

def width
  @grid.max(&:length) * @tile_width
end