Private
Public Access
1
0
Files
MineSeeker/assets/js/mine-seeker/grid/grid.js

102 lines
1.9 KiB
JavaScript

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 (let i = 0, j = this.state.row * this.state.col; i < j; i++) {
obj.push(
0 < this.state.mines
? 'm'
: 'w',
);
this.state.mines--;
}
return obj;
}
shuffleSet(obj) {
return obj.sort(function() {
return Math.round(Math.random()) - .5;
});
}
createGrid(obj) {
let grid = [[]],
row = 0,
col = 0;
for (let i = 0, j = obj.length; i < j; i++) {
grid[row][col] = obj[i];
if (15 === col && 15 !== row) {
row++;
col = 0;
grid.push([]);
} else {
col++;
}
}
return grid;
}
checkMine(field, i, j) {
return 'undefined' !== typeof field[i] && 'undefined' !== typeof field[i][j] && 'm' === field[i][j];
}
isThereMine(obj, row, col) {
if (this.checkMine(obj, row, col)) {
return 1;
}
return 0;
}
numberingGrid(obj) {
let nbr = 0;
for (let i = 0; i < this.state.row; i++) {
for (let j = 0; j < this.state.col; j++) {
if ('w' === obj[i][j]) {
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;