App 6: Make a Game, Snake in Pygame / Build Snake
Lesson 6 of 10
Food and growing
Put food in a random empty cell. When the head reaches it, don't remove the tail that frame, so the snake grows, and place new food.
Key points
- random.randrange for positions
- Skip snake.pop() when eating
- Food must not land on the snake
import random
def new_food():
while True:
spot = (random.randrange(30), random.randrange(30))
if spot not in snake:
return spot
food = new_food()
# in the update step:
if snake[0] == food:
food = new_food()
else:
snake.pop()Your turn
Add food that makes the snake grow.
Quiz · +10 XP
How does the snake grow?
Log in to save progress and earn XP.