开发者

jquery recursive function

开发者 https://www.devze.com 2023-03-04 22:20 出处:网络
Im trying to make a minesweeper game in jquery. When a user clicks on a table cell, a check is done to see if there is a number or an x in the square. If there is not, this function is called and the

Im trying to make a minesweeper game in jquery.

When a user clicks on a table cell, a check is done to see if there is a number or an x in the square. If there is not, this function is called and the table cell is passed to it.

The function returns all the adjacent squares to the clicked square, and they are then uncovered.

The question is, from the selection of adjacent squares initially returned, how can i check if any of them are empty, and if they are, get the squares adjacent to them, and uncover them and check if any of them are empty....until all empty squares that were adjacent to any adjacent squares to the clicked one are uncovered?

if (isEmptySquare(this)) {
    emp = adjacentSquares(this);
    $(emp).each(function() {
        $(this).removeClass('covered').addClass('uncovered');
    });
}

function adjacentSquares(square) {
    //Find the row and column of the current td(square)
    var thisRow = $(square).parent().parent().children().index($(square).parent());
    var thisCol = $(square).parent().children().index($(square));
    var prevRow = (thisRow - 1);
    var nextRow = (thisRow + 1);

    if (thisCol == 0) {
        sliceFrom = 0;
    } else {
        sliceFrom = (thisCol - 1);
    }

    //Select all the adjacent td's to the current td, then merge the adjacent cells into a variable
    var above = $('tr:eq(' + prevRow + ')').children('td').slice((sliceFrom), (thisCol + 2));
    var below = $('tr:eq(' + nextRow + ')').children('td').slice((sliceFrom), (thisCol + 2));
    var aboveBelow = $.merge(above, below);
    var prevNext = $.merge(($(square).next('开发者_JS百科td')), ($(square).prev('td')));
    var adjacents = $.merge(aboveBelow, prevNext);

    return adjacents;
}

function isEmptySquare(square) {
    if ($(square).filter(function() {
        return !/[0-9]/.test($(square).text());
    }).not(":contains('x')").length > 0) {
        return true;
    }
    else {
        return false;
    }
}


This is a more familiar problem than you might think. You can achieve what you need by implementing the Flood Fill algorithm.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号