I'm confused on a do while function in a Snake Game I'm trying to learn. This code generates a new apple in a random div. From what I'm reading here, it says as long as the square does contain the class of "snake", then add the class of "apple" to the randomly generated square. But I thought it would be the opposite, as when a square has the class of "snake" you DON'T want an apple generated. I'm sure I'm utterly misunderstanding this, please help!
function generateApples() {
do {
//generate a random number
appleIndex = Math.floor(Math.random() * squares.length)
} while (squares[appleIndex].classList.contains('snake'))
squares[appleIndex].classList.add('apple')
}
generateApples()
1 Answer 1
But I thought it would be the opposite, as when a square has the class of "snake" you DON'T want an apple generated.
That's what the code's logic is doing.
If the random square chosen is part of the snake:
} while (squares[appleIndex].classList.contains('snake'))
then that's not desirable, so the loop repeats - and again and again, until the condition is no longer fulfilled.
Once the condition is no longer fulfilled, you'll know that the random square's classList does not contain snake, and an apple can be added to it.
You could think of it as
do {
// stuff
} while (retryCondition);
repeating the loop while retryCondition is true, and stopping the loop only once retryCondition is false.
7 Comments
for (let i = 0; i < 3; i++) console.log(i); console.log('done'); will log 0 1 2 done, not done 0 1 2, that wouldn't make sense