2

Дана координатная плоскость 50х50, в случайной точке генерируется бомба (функция setBomb()), после взрыва нужно закрасить окружность, радиусом в 3 точки (функция soundSpread). Если бомба генерируется далеко от границ, то все нормально:

введите сюда описание изображения

Если же бомба генерируется рядом с границами, то начинаются проблемы:

введите сюда описание изображения

Подскажите, как можно заставить программу красить точки до тех пор, пока координаты не столкнутся с границами?

let field = document.getElementById('field')
    function addCell(field) {
        let coordinates = [], i, j;
        for(i = 0; i<50; i++) {
            coordinates[i] = new Array()
            for (j = 0; j<50; j++){
                let cell = document.createElement('div')
            cell.setAttribute('class','cell')
                cell.setAttribute('x',(i+1).toString())
                cell.setAttribute('y',(j+1).toString())
                coordinates[i][j] = cell
            field.appendChild(cell)
            }
        } return coordinates
    }
    
    let coordinates = addCell(field)
    
    function setBomb(coordinates) {
        function getRandomInt(max) {
            return Math.floor(Math.random() * max);
        }
       let x = getRandomInt(coordinates.length)
        let y = getRandomInt(coordinates.length)
    
    
        let bombPlace = coordinates[x][y]
        bombPlace.setAttribute('class', 'affected')
       function soundSpread(x,y) {
            for(let i = 0; i<3; i++) {
    
                    coordinates[x+i][y+i].setAttribute('class', 'affected')
                    coordinates[x-i][y-i].setAttribute('class', 'affected')
                    coordinates[x+i][y-i].setAttribute('class', 'affected')
                    coordinates[x-i][y+i].setAttribute('class', 'affected')
                    coordinates[x+(i+1)][y].setAttribute('class', 'affected')
                    coordinates[x][y+(i+1)].setAttribute('class', 'affected')
                    coordinates[x-(i+1)][y].setAttribute('class', 'affected')
                    coordinates[x][y-(i+1)].setAttribute('class', 'affected')
    
    
            }
        }
       soundSpread(x,y)
    
    
    }
    
    setBomb(coordinates)

1 ответ 1

0
function setAffected(coordinates, x, y) {
  if (x >= 0 && x < coordinates.length && y >= 0 && y < coordinates[x].length)
    coordinates[x][y].setAttribute('class', 'affected');
}

...
  for (let i = 0; i < 3; i++) {
    setAffected(coordinates, x + i, y + i);
    ...
1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.