我正在为我的roguelike游戏创建一张地图,我已经偶然发现了一个问题。我想创建一个二维对象数组。在我以前的C ++游戏中,我做到了这一点:
class tile; //found in another file.
tile theMap[MAP_WIDTH][MAP_HEIGHT];
我无法弄明白我应该如何使用Ruby。
答案 0 :(得分:4)
theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
答案 1 :(得分:2)
2D阵列没有汗水
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) }
答案 2 :(得分:1)
使用数组数组。
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}
答案 3 :(得分: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"