javascript 扫雷程序 floodfill 算法没有正常工作

javascript minesweeper floodfill algorithm not working as it should

我正在尝试编写我的第一个简单的扫雷游戏。为了显示空白字段,我编写了一个简单的洪水填充算法,但它没有按预期工作。这是一段代码:

function reveal(a,b){
var fieldId = getFieldId(a,b);  

/*
cells are stored in array fields[]. Each cell is an object {x: x,y: y, hasBomb: boolean,
hasBeenDiscovered: boolean}. Function getFieldId returns array key for (x,y) cell.
*/

if(a < 0 || a > boardWidth-1){return}
if(b < 0 || b > boardHeight-1){return}

if(fields[fieldId].hasBeenDiscovered == true){return}

if(getNeighbourNumber(a,b) > 0){
    document.getElementById(a+'x'+b).innerHTML = getNeighbourNumber(a,b);
    document.getElementById(a+'x'+b).style.backgroundColor = 'white';
    document.getElementById(a+'x'+b).setAttribute('discovered',1);
    fields[fieldId].hasBeenDiscovered = true;
    return
}else if(getNeighbourNumber(a,b) == 0){
    document.getElementById(a+'x'+b).innerHTML = ' ';
    document.getElementById(a+'x'+b).style.backgroundColor = 'white';
    document.getElementById(a+'x'+b).setAttribute('discovered',1);  
    fields[fieldId].hasBeenDiscovered = true;


}

    reveal(a,b);
    console.log('0 ' + '0');
    reveal(a+1,b);
    console.log('+1' + ' ' + '0');
    reveal(a-1,b);
    console.log('-1 ' + '0');
    reveal(a,b+1);
    console.log('0 ' + '+1');
    reveal(a,b-1);
    console.log('0 ' + '-1');
    reveal(a-1,b-1);
    console.log('-1 ' + '-1');
    reveal(a-1,b+1);
    console.log('-1 ' + '+1');
    reveal(a+1,b+1);
    console.log('+1 ' + '+1');
    reveal(a+1,b-1);
    console.log('+1 ' + '-1');
    console.log('------------');

}

当发现北、西北和西邻居有邻居炸弹的空单元格时,即使其他邻居(南、东南、西、东、东北)是空的,floodfill 也会显示这些单元格。我是初学者编码员,我不明白为什么这段代码不能完全正常工作。任何帮助将不胜感激:)

编辑:控制台日志仅用于调试尝试。

我很高兴地说,您编写了很棒的代码,阅读和理解代码非常容易。

你只需要在 revealField 函数中检查一个小东西,这里你需要记住的一件事是,当你从属性中获取值时,它总是以字符串形式给你,所以你需要将字符串解析为数字以十进制为基数。

function revealField(){
    var x = this.getAttribute('x');
    var y = this.getAttribute('y');
    x = parseInt(x, 10);
    y = parseInt(y, 10);

    var fieldId = getFieldId(x,y);

    if(fields[fieldId].hasBomb == true){
        document.getElementById(x+'x'+y).innerHTML = 'B';
        this.style.backgroundColor = 'brown';
        this.setAttribute('hasBomb', 1);
        removeEvents();
        alert('Bomba! Przegrales!');
    }else{
        this.style.backgroundColor = 'white';
        this.setAttribute('discovered',1);
        reveal(x,y);
        if(validateVictory() == true){
            removeEvents();
            alert('Brawo! Odkryles wszystkie bomby!');          
        }   
    }
}

这是您更新后的fiddle