# Copyright 2009, Chris F.A. Johnson # Released under the terms of the GNU General Public License # http://www.gnu.org/licenses/gpl.html #@ These bash functions store a grid as a single string. #@ They work only on square grids, NxN #@ Most require the size of the grid to be stored in $gridsize #@ DESCRIPTION: Fill N x N grid with a character #@ USAGE: initgrid gridname size character initgrid() { [ $# -lt 2 ] && return 1 local grid size=$(( $2 * $2 )) printf -v grid "%$size.${size}s" ' ' eval "$1=\${grid// /${3:-.}}" } #@ DESCRIPTION: Store row/column's index into string in $_GRIDPOS #@ USAGE: _gridpos row column [gridsize] _gridpos() { [ $# -lt 2 ] && return 1 local gridsize=${3:-$gridsize} _GRIDPOS=$(( ($1 - 1) * $gridsize + $2 )) } #@ DESCRIPTION: Get character from grid in row Y, column X #@ USAGE: getgrid gridname row column var getgrid() { [ $# -lt 4 ] && return 1 _gridpos $2 $3 eval "$4=\${$1:_GRIDPOS-1:1}" } #@ DESCRIPTION: Insert character int grid at row and column #@ USAGE: putgrid gridname row column char putgrid() { local left right _GRIDPOS _GRID gridname=$1 _gridpos $2 $3 eval "left=\${$1:0:_GRIDPOS-1} eval "right=\${$1:_GRIDPOS} _GRID=$left$4$right eval "$gridname=\$_GRID" } #@ DESCRIPTION: print grid to stdout #@ USAGE: showgrid gridname showgrid() { local _grid eval "_grid=\${$1}" while [ -n "$_grid" ] do row=${_grid:0:gridsize} printf "%s\n" "$row" _grid=${_grid#"$row"} done }