【发布时间】:2010-07-28 20:37:24
【问题描述】:
我正在为我的 roguelike 游戏创建地图,但我已经偶然发现了一个问题。我想创建一个二维对象数组。在我之前的 C++ 游戏中,我是这样做的:
class tile; //found in another file.
tile theMap[MAP_WIDTH][MAP_HEIGHT];
我不知道该如何使用 Ruby。
【问题讨论】:
标签: ruby arrays object map roguelike
我正在为我的 roguelike 游戏创建地图,但我已经偶然发现了一个问题。我想创建一个二维对象数组。在我之前的 C++ 游戏中,我是这样做的:
class tile; //found in another file.
tile theMap[MAP_WIDTH][MAP_HEIGHT];
我不知道该如何使用 Ruby。
【问题讨论】:
标签: ruby arrays object map roguelike
theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
【讨论】:
theMap.each {|y| y.each {|x| x.draw } }
theMap.flatten.each {|x| x.draw} 工作(我知道它会很慢)?
使用数组的数组。
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}
【讨论】:
二维数组不费吹灰之力
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) }
【讨论】:
# 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"
【讨论】: