0

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()
asked Aug 8, 2021 at 4:50

1 Answer 1

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.

answered Aug 8, 2021 at 4:52
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. And once the loop stops, the apple class list gets added?
Yes, to the random square that wasn't a part of the snake.
I think that's where my confusion comes in - inherently, why does something get executed after a loop stops? Is that what the loop by its nature does - loops around and around and then once it stops, it executes? And obviously there are some basic programming fundamentals I'm not getting. Apologies for the newbness.
?? No, the loop will execute the code inside it until the loop stops, not the other way around. Another example 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
Yes, once the loop stops, the lines following the loop block run
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.