import React from 'react'; class Grid extends React.Component { constructor() { super(); this.state = { row: 16, col: 16, mines: 51, set: [] }; this.state.grid = this.numberingGrid( this.createGrid( this.shuffleSet( this.createSet( this.state.set ) ) ) ); } createSet(obj) { for (var i = 0, j = this.state.row * this.state.col; i < j; i++) { obj.push( this.state.mines > 0 ? "m" : "w" ); this.state.mines--; } return obj; } shuffleSet(obj) { return obj.sort(function () { return Math.round(Math.random()) - .5; }); } createGrid(obj) { var grid = [[]], row = 0, col = 0; for (var i = 0, j = obj.length; i < j; i++) { grid[row][col] = obj[i]; if (col === 15 && row !== 15) { row++; col = 0; grid.push([]); } else { col++; } } return grid; } checkMine(field, i, j) { return typeof field[i] !== 'undefined' && typeof field[i][j] !== 'undefined' && field[i][j] === 'm'; } isThereMine(obj, row, col) { if (this.checkMine(obj, row, col)) { return 1; } return 0; } numberingGrid(obj) { var nbr = 0; for (var i = 0; i < this.state.row; i++) { for (var j = 0; j < this.state.col; j++) { if (obj[i][j] === 'w') { nbr = 0; nbr += this.isThereMine(obj, i - 1, j); nbr += this.isThereMine(obj, i - 1, j - 1); nbr += this.isThereMine(obj, i - 1, j + 1); nbr += this.isThereMine(obj, i, j - 1); nbr += this.isThereMine(obj, i, j + 1); nbr += this.isThereMine(obj, i + 1, j); nbr += this.isThereMine(obj, i + 1, j + 1); nbr += this.isThereMine(obj, i + 1, j - 1); obj[i][j] = nbr; } } } return obj; } } export default Grid;