Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 09.06.2014, 20:35
Аспирант
Отправить личное сообщение для IVAAAAN Посмотреть профиль Найти все сообщения от IVAAAAN
 
Регистрация: 04.07.2013
Сообщений: 47

Генерация непересекающихся блоков
Есть код js:
var W = 800, H = 510,
        box    = null, boxW = 80, boxH = 80, coords = [], countClicks = 0, amount = 3, level=1;    
                 
function start(){
    window.arrayNums = rand(amount, amount*2, amount).sort();   
    for(var i = 0; i <amount; i++) {
        generate(arrayNums[i]);
     }
     var numbersResult = new Array();
            $(".box").click(function(){
                $(this).html($(this).data('number'));
                numbersResult.push(parseInt($(this).data('number')));
                countClicks++;
                console.log(countClicks);
                if(countClicks==amount){
                    console.log(numbersResult);
                    console.log(arrayNums);
                    for(var i = 0; i<amount;i++){
                        
                            if(numbersResult.toString()==arrayNums.toString()){
                                countClicks=0;
                                console.log('Win!');
                                amount++;
                                $("#game-area").html('');
                                level++;
                                start();
                                $(".level").html(level);
                                

                            }

                            else{
                                console.log('Loh!');
                                $("#game-area").html('');
                                countClicks=0;
                                amount=3;
                                level=1;
                                start();
                                $(".level").html(level);


                            }
                            
                        
                    }
                    
                }
            
        });
        setTimeout(function(){
            $(".box").each(function(){
                $(this).html('?')
            });
        }, (1000*amount)/2);

}
$(document).ready(function(){
        box = document.getElementById("game-area");
        box.style.width  = W + 'px';
        box.style.height = H + 'px';
        $(".level").html(level);

        start();
    
        
});


function getRandomInt(min, max)
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function rand(max, min, length){
    var result = [],
        resultSorted = [];

    if(typeof max !== 'number') return Math.random();
    if(typeof min !== 'number') return Math.floor(Math.random() * ++max);

    if(min > max) min = [max, max = min][0];                 

    if(!length || typeof length !== 'number') return Math.floor(Math.random() * (max - min + 1)) + min;

    if(length > max - min + 1) throw new RangeError('invalid length.');

    for(var j = 0, random, index; j < length; j++, max--){
        random = Math.floor(Math.random() * (max - min + 1)) + min;

        for(index = j; index && resultSorted[index-1] <= random; index--) random++; 

        result.push(random);
        resultSorted.splice(index, 0, random);
    }

    return result;
}

function generate(number) {
    var x = 0, y = 0, i = 0;
    do {
        x = Math.floor(Math.random() * ( W - boxW ));
        y = Math.floor(Math.random() * ( H - boxH ));
                    
        i++;
                
    } while((i < amount) && intersect(x, y));
   
      if(i < amount) {
                coords.push({ 
                        x : x,
                        y : y
                });
                        
                addBox(x, y, number);
        }
};
 
function intersect(x, y) {
    var i = coords.length;
    
    while(i-- > 0) {
        if(Math.abs(coords[i].x - x) > boxW || Math.abs(coords[i].y - y) > boxH) continue;
        return true;
    }
        
    return false;
}
 
function addBox(x, y, num) {
    
    var div = document.createElement("div");
    div.className    = "box";
    div.style.left   = x + 'px';
    div.style.top    = y + 'px';
    div.style.width  = boxW + 'px';
    div.style.height = boxH + 'px';
    div.setAttribute('data-number', num);   
    div.innerHTML = num;
    box.appendChild(div);
}


Это генерирует блоки с числами. Но случается ситуация, когда блоков генерится не 3, а 2. Не 4, а 3. И т.д. В основном в начале 3 блока добавляет, но на 1 случай из 10 генерит на один меньше. В чем причина этого бага?
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Скрипт выравнивания высоты блоков razorg1991 Элементы интерфейса 13 15.01.2017 00:04
Сортировка блоков по параметрам webmanss Элементы интерфейса 17 18.06.2016 20:04
Удаление глюков при появлении и исчезании блоков Сершей jQuery 5 25.08.2013 03:20
Генерация блоков IVAAAAN Общие вопросы Javascript 27 08.07.2013 19:51
Печать невидимых блоков mixeeff Events/DOM/Window 7 11.03.2009 11:41