0

我正在为我的 roguelike 游戏创建地图,但我已经偶然发现了一个问题。我想创建一个二维对象数组。在我之前的 C++ 游戏中,我这样做了:

class tile; //found in another file.

tile theMap[MAP_WIDTH][MAP_HEIGHT];

我不知道我应该如何用 Ruby 做到这一点。

4

4 回答 4

4
theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
于 2010-07-28T20:41:04.713 回答
2

使用数组数组。

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

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

还要查看Matrix课程:

require 'matrix'
Matrix.build(3,3){|i, j| i+j}
于 2010-07-28T20:41:25.410 回答
2

二维阵列不费吹灰之力

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]] 

要加载 2D 数组,请尝试以下操作:

rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }
于 2010-07-28T20:42:24.040 回答
0
# 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"
于 2010-07-28T22:05:49.243 回答