I’ve been working on a small game these days. I found myself in a situation where I had to scale up a tilemap I had made. So that the brick walls could be more.
A tilemap can be represented as a two-dimensional array. What I had to do here, is take a matrix of the following kind:
1 2 3
4 5 6
7 8 9
and turn it into
1 1 2 2 3 3
1 1 2 2 3 3
4 4 5 5 6 6
4 4 5 5 6 6
7 7 8 8 9 9
7 7 8 8 9 9
Notice the pattern? I’m doing a 2x resize here. Each of those numbers represent a tile.
Here’s a quick way to do it in Ruby:
# This method takes every element in an array and duplicates it
def repeat_twice(array)
array.collect do |i|
[i, i]
end.flatten(1)
end
tilemap = [[1,2,3], [4,5,6], [7,8,9]]
# In each row, repeat each tile twice
widened_map = tilemap.collect do |row|
repeat_twice(row)
end
# Now repeat each row twice to scale it vertically
scaled_tilemap = repeat_twice(widened_map)
# Print out the scaled_tilemap and you'll see the result
scaled_tilemap.each do |line|
p line
end
You can easily modify this to scale up by higher proportions.
There’s a lot to learn from making games. I think everyone should write a game sometime.