I have a MapTile class which holds a tile sprite and the tile’s attribute. I want to create a 2D array which holds for example 100 tiles in a 10×10 grid. I have drawn a tile map using a plain old 2D array holding only the tile sprite and that worked fine. However, now when I assign a tile sprite to the 2D Array named mapData containing MapTile classes and using mapData[i][j].tileSprite = tileNum, every element in the column is assigned the tileNum value. I have tried everything I could think of to get this to work. I am a C++ programmer new to Ruby.
class MapTile
attr_accessor :tileSprite, :attribute
def initialize(sprite, attr)
@tileSprite = sprite
@attribute = attr
end
def tileSprite
@tileSprite
end
def attribute
@attribute
end
end
def array2D(width,height)
a = Array.new(width, MapTile.new(123,0))
a.map! { Array.new(height, MapTile.new(123,0)) }
return a
end
@mapData = array2D(@mapSize,@mapSize)
mapData[1][j].tileSprite = tileNum #Now every tileSprite in column 1 is tileNum
Solution
Changed the array2D method to
def array2D(width,height)
a = Array.new(width) { MapTile.new(10,0)}
a.map! { Array.new(height) { MapTile.new(10,0) } }
return a
end
Thanks Michael!
You are using the same object for each array element. Try
Array.new(width) { MapTile.new(123,0) }instead.From the docs:
BTW: There are some things in your code that are rather unidiomatic Ruby, you may want to run that by the Code Review Stack Exchange.