views:

54

answers:

4

I am creating a map for my roguelike game and already I stumbled on a problem. I want to create a two dimensional array of objects. In my previous C++ game I did this:

class tile; //found in another file.

tile theMap[MAP_WIDTH][MAP_HEIGHT];

I can't figure out how I should do this with Ruby.

+2  A: 
theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
Adrian
Thank you. How can I call the objects functions in that array? I need to cycle through the array and call each objects draw -function.
Shub Niggurath
@Shub: `theMap.each {|y| y.each {|x| x.draw } }`
Adrian
+1  A: 

Use arrays of arrays.

board = [
 [ 1, 2, 3 ],
 [ 4, 5, 6 ]
]

x = Array.new(3){|i| Array.new(3){|j| i+j}}

Also look into the Matrix class:

require 'matrix'
Matrix.build(3,3){|i, j| i+j}
Marc-André Lafortune
I am familiar with multidimensional arrays and matrices in general, my problem lies with not knowing how to declare one as an array of objects in ruby.
Shub Niggurath
You don't need to declare things in Ruby, thanks to dynamic typing.
Marc-André Lafortune
Note: Ruby >= 1.9.2 will only support rectangular matrices.See: http://svn.ruby-lang.org/repos/ruby/tags/v1_9_2_rc1/NEWS
Baju
I guess I'm supposed create an object inside my 2D-array with .new() like Adrian showed me. That's cool and all, but what do I use to call an object that I didn't declare with any name? I must be stupid :(
Shub Niggurath
Looks like theMap.each { |i| i.each { |j| j.function } } works. It's weird having the objects seperate from the array, at least for me.
Shub Niggurath
A: 

2D arrays are no sweat

array = [[1,2],[3,4],[5,6]]
 => [[1, 2], [3, 4], [5, 6]] 
array[0][0]
 => 1 
array.flatten
 => [1, 2, 3, 4, 5, 6] 
array.transpose
 => [[1, 3, 5], [2, 4, 6]] 

For loading 2D arrays try something like:

rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }
nicholasklick
A: 
# Let's define some class
class Foo
  # constructor
  def initialize(smthng)
    @print_me = smthng
  end
  def print
    puts @print_me
  end
# Now let's create 2×2 array with Foo objects
the_map = [
[Foo.new("Dark"), Foo.new("side")],
[Foo.new("of the"), Foo.new("spoon")] ]

# Now to call one of the object's methods just do something like
the_map[0][0].print # will print "Dark"
the_map[1][1].print # will print "spoon"
TweeKane