2011-05-11 111 views
0

我試圖在jquery中做一個掃雷遊戲。jquery遞歸函數

當用戶點擊表格單元格時,會進行檢查以查看正方形中是否有數字或x。如果沒有,則調用此函數並將表格單元傳遞給它。

該函數將所有相鄰的正方形返回到被點擊的正方形,然後揭開它們。

問題是,從最初返回的相鄰方塊的選擇中,我如何檢查它們中的任何一個是否爲空,如果它們是,則獲取與它們相鄰的方塊,並揭開它們並檢查它們中的任何一個是否空......直到所有與鄰接的方格相鄰的所有空方格都被揭開了?

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('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; 
    } 
} 

回答

1

這是比您想象的更爲熟悉的問題。你可以通過實施Flood Fill algorithm來實現你所需要的。

+0

乾杯。在查看洪水填充後,我發現了我所需要的@ http://www.htmlgoodies.com/primers/jsp/article.php/3622321/Javascript-Basics-Part-12.htm – callumander 2011-05-12 17:23:02