簡體   English   中英

如何在Ruby中為2D數組中的類對象分配值

[英]How to assign values to class objects in a 2D array in Ruby

我有一個MapTile類,其中包含MapTile貼精靈和MapTile貼的屬性。 我想創建一個2D數組,例如在10x10網格中包含100個圖塊。 我已經使用僅保留瓦片精靈的普通2D數組繪制了瓦片地圖,並且效果很好。 但是,現在,當我向名為mapData的2D數組( mapData包含MapTile類)分配平鋪精靈時,並使用mapData[i][j].tileSprite = tileNummapData[i][j].tileSprite = tileNum列中的每個元素分配tileNum值。 我已經盡我所能想出一切來使它起作用。 我是Ruby的C ++程序員。

class MapTile
attr_accessor :tileSprite, :attribute

    def initialize(sprite, attr)
    @tileSprite = sprite
    @attribute = attr
    end 

    def tileSprite
        @tileSprite
    end

    def attribute
        @attribute
    end

end



def array2D(width,height)
  a = Array.new(width, MapTile.new(123,0))
  a.map! { Array.new(height, MapTile.new(123,0)) }
  return a
end


@mapData = array2D(@mapSize,@mapSize)

mapData[1][j].tileSprite = tileNum  #Now every tileSprite in column 1 is tileNum

將array2D方法更改為

def array2D(width,height)
a = Array.new(width) { MapTile.new(10,0)}
a.map! { Array.new(height) { MapTile.new(10,0) } }
return a
end

謝謝邁克爾!

每個數組元素都使用相同的對象。 請嘗試使用Array.new(width) { MapTile.new(123,0) }

文檔

# only one copy of the object is created 
a = Array.new(2, Hash.new)

# here multiple copies are created 
a = Array.new(2) { Hash.new }

順便說一句:您的代碼中有些東西是相當獨特的Ruby,您可能希望通過Code Review Stack Exchange來運行它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM