Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

Moving objects in javascript (the start of the snake game)

Does anyone have an idea how to make these 3 colored squares move around the perimeter of the board, and not like now, i.e. in lines? (lines 57-78) https://codepen.io/diana-larussa/pen/ExgpXzo

function timer() {
    ttl--

    divElement = document.querySelectorAll('div')

    divElement[nr_boxu].style.backgroundColor = "#6d5dfc"
    divElement[nr_boxu].value = 0

    nr_boxu = nr_boxu + 1
    divElement[nr_boxu].style.backgroundColor = "#F25270"
    divElement[nr_boxu+1].style.backgroundColor = "#F25270"
    divElement[nr_boxu+2].style.backgroundColor = "#F25270"

    spanTimer.innerHTML = "TIME: " + ttl
    //if (nr_boxu>gridDOMElement.value-4) stop()

    /*if (divElement[nr_boxu] == gridDOMElement.value - 4) {
        divElement[gridDOMElement.value + 1].style.backgroundColor = "#F25270"
    }*/

    if (ttl == 0) stop()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think for each grid size it is possible to generate perimeter sequence of indices and timer() function could pick 4 of those indices to update.

For example, in this grid 5x4:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...