js九宫格算法

var grid = [];
var RowCells = 3;

function initGrid() {
for (var nRow = 0; nRow < RowCells; nRow++) {
grid[nRow] = [];
for (var nCol = 0; nCol < RowCells; nCol++) {
grid[nRow][nCol] = -1;
}
}
}

function showGrid() {
for (var nRow = 0; nRow < RowCells; nRow++) {
for (var nCol = 0; nCol < RowCells; nCol++) {
document.write(grid[nRow][nCol] + ' ');
}
document.write('<br/>');
}
}

var position = {
nRow: 0,
nCol: 1
}

function fillData() {
for (var nData = 1; nData <= RowCells * RowCells; nData++) {
grid[position.nRow][position.nCol] = nData;
getNextPosition()
}
}

function getNextPosition() {
var newRow = (position.nRow - 1 + RowCells) % RowCells;
var newCol = (position.nCol - 1 + RowCells) % RowCells;
if (grid[newRow][newCol] == -1) {
position.nRow = newRow;
position.nCol = newCol;
}
else {
position.nRow = (position.nRow + 1) % RowCells;
}
}

initGrid();
fillData();
showGrid();

猜你喜欢

转载自www.cnblogs.com/zxk5625/p/10290029.html