class

Collections::Grid(T)

Inherits Reference < Object

Constructors

new(rows : Int32, cols : Int32, default_value : T)

Initialize the grid with the given dimensions

Source

Class methods

from_string(text : String, default_value : T, & : Char, Int32, Int32 -> T) : Grid(T)

Builds a grid from a multi-line string, mapping each character to a cell value via the block. Each line becomes a row (x), each column a y; the grid width is the length of the longest line, and shorter rows are left at default_value.

grid = Collections::Grid(Int32).from_string("12\n34", 0) { |char, _x, _y| char.to_i }
grid.get(1, 1) # => 4
Source
from_string(text : String, default_value : Char = '.') : Grid(Char)

Builds a Grid(Char) from a multi-line string, one character per cell. default_value is the value returned for cells outside a ragged row.

grid = Collections::Grid(Char).from_string("#..\n.#.")
grid.get(1, 1) # => '#'
Source

Instance methods

blocked?(x : Int32, y : Int32) : Bool
Source
cols
Source
flood_fill(x : Int32, y : Int32, new_value : T, diagonal : Bool = false) : Array(Point)

Flood fills the connected region of cells that share the start cell's value, replacing each with new_value, and returns the filled points in fill order. Connectivity is orthogonal by default; pass diagonal: true to also spread across diagonals.

Cells are matched by value (not by blocked?), so this works on any grid.

Source
get(x : Int32, y : Int32) : T
Source
neighbors(x : Int32, y : Int32, filter_blocked : Bool = true, diagonal : Bool = false, toroidal : Bool = false) : Array(Point)

Get valid neighbors for the given cell. Orthogonal (up/down/left/right) by default; pass diagonal: true to also include the four diagonal cells.

Pass toroidal: true to treat the grid as a torus: neighbors wrap across the edges (via #wrap) instead of being clipped. On small grids where opposite neighbors land on the same cell, the result is deduplicated and the origin cell itself is never included.

Source
region(x : Int32, y : Int32, diagonal : Bool = false) : Array(Point)

Returns the connected region of cells that share the start cell's value, in traversal order, without modifying the grid. Connectivity is orthogonal by default; pass diagonal: true to also spread across diagonals.

Cells are matched by value (not by blocked?), so this works on any grid.

Source
rows
Source
set(x : Int32, y : Int32, value : T)
Source
shortest_path(start : Tuple(Int32, Int32) | Array(Int32) | Point, goal : Tuple(Int32, Int32) | Array(Int32) | Point, filter_blocked : Bool = true) : Tuple(Int32, Array(Point)) | Nil

Find the shortest path between two points using BFS

Source
wrap(x : Int32, y : Int32) : Point

Wraps a coordinate onto the grid, so values off one edge reappear on the opposite edge (toroidal / wrap-around indexing).

grid = Collections::Grid.new(5, 5, 0)
grid.wrap(-1, 5) # => Point(4, 0)
Source

Nested types