R_C
R_C

Reputation: 353

Python Pygame Snake Apple Spawning Inside obstacles

I am making a snake game with Python. I am following Sentdex's Pygame tutorials, but I wanted to try to make obstacles, so I went off and tinkered with the code a bit.

How do I make the apple stop spawning inside other foreign obstacles?

Upvotes: 1

Views: 308

Answers (1)

skrx
skrx

Reputation: 20478

To generate random coordinates, you can use a while loop and random.randrange to get new x and y coords, check if the coords are blocked, if yes, continue to generate new coords and check again if the area is blocked, if it's not blocked return the coords. Of course if the whole map is filled, this loop will run infinitely, so you'd need a way to break out of it in this special case or quit the game.

Alternatively you could create a list of the non-blocked coords and then use random.choice to pick one coord pair.

Upvotes: 1

Related Questions