// https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix // convert a 1D array into a 2D matrix export function toMatrix(array, width) { return array.reduce( (rows, key, index) => (index % width == 0 ? rows.push([key]) : rows[rows.length - 1].push(key)) && rows, [] ); } // convert an image into a black and white image export function picToBlackAndWhite(pixels, width, height) { return pixels.reduce((acc, pixel, index) => { if (index % 4 == 0) { const count = pixels[index] + pixels[index + 1] + pixels[index + 2]; const colour = count >= 255 ? 255 : 1; acc.data[index] = colour; acc.data[index + 1] = colour; acc.data[index + 2] = colour; acc.data[index + 3] = 255; } return acc; }, new ImageData(width, height)); } // convert an ImageData into a 2D array of boolean (0, 1) values export function picToBoard(pixels, width, height) { const flat = pixels.reduce((acc, pixel, index) => { if (index % 4 == 0) { const count = pixels[index] + pixels[index + 1] + pixels[index + 2]; const value = count >= 255 ? 1 : 0; acc.push(value); } return acc; }, []); return toMatrix(flat, Math.max(width, height)); }