vendredi 22 juillet 2016

Overlapping random divs

I'm making a simple game (whack a mole), the game works like this: Every time you press the start button, it will place 10 divs into the DOM. The divs will be placed randomly into the DOM.

My problem is that they overlap each other and sometimes they're place outside of their container.

I'd like to know how can i place them randomly inside the container without overlapping each other, i prefer not to use a grid to place them, i want them to be randomly distributed across the container.

here's the main function:

function randomPos(size){
var result = new Array();
var height = (document.getElementById('field').clientHeight);
var width = document.getElementById('field').clientWidth;
for (var i = 0; i < size; i++) {
    var obj = {};
    var posY = Math.floor(Math.random() * height);
    var posX = Math.floor(Math.random() * width);
    if (result.length == 0){
        obj.x = posX;
        obj.y = posY;
        result.push(obj);
    }
    else{
        var flag = true;
        for (var j = 0; j < i && flag; j++){
            if (result[j].y == posY && result[j].x == posX){
                flag = false;
            }
        }
        if(flag){
            obj.x = posX;
            obj.y = posY ;
            result.push(obj);
        }
        else{
            i--;
        }
    }
}
return result;
}

here's a jsfiddle




Aucun commentaire:

Enregistrer un commentaire