Your task: Code your own version of the classic game "Snake." To make it a bit easier, we have it broken down into steps here. Good luck!
Target practice for turtles (optional): This might be a useful warm-up exercise to do before you tackle the snake game. Some of the problems you need to solve here (checking x and y coordinates, having the program do something if/until the turtle reaches a certain part of the screen) are the same ones you'll need to solve for snake.
With hints: We've written a tiny bit of the code for you to get you started.
Without hints: If you want to try starting from scratch.
Don't worry about making the snake a certain length yet; just let the tail stay in the middle of the screen. Once the snake hits the edge of the screen, print "Game over."
Some turtle functions you might find useful here:
my_turtle.dot(10) # You can change the number to change the size of the dot
my_turtle.xcor() # How far left or right is your turtle?
my_turtle.ycor() # How far up or down is your turtle?
The coordinates of the screen go from -200 to 200.
There is a function called "onkey" that will run a function of your choice when a key is pressed. This is how it works:
screen = Screen() # This gives you a variable for the screen
screen.listen() # Listen for key presses
screen.onkey(my_function_name, "Right")
my_function_name is a function that you define yourself. In this case, your function would run every time you press the right arrow key.
The way I solved this problem involved adding and removing things from lists. Here are some list-related functions that might be useful for this step:
my_list = ['ugh', 'my', 'snake', 'game', 'is', 'going', 'terribly']
my_list.pop(0) # Remove the first thing from the list
my_list.append("awesome") # Add “awesome” to the end of the list
length = len(my_list) # Check how many things are in the list
print(my_list)
OUTPUT: ['my', 'snake', 'game', 'is', 'going', 'terribly', 'awesome']
print(length)
OUTPUT: 7
Don’t panic if your snake looks like a weird caterpillar (as in video 3a)! This just means you need to take control of when the screen updates. This is how you can do that:
screen.tracer(0, 0) # This turns off the animations – run this once at the start
screen.update() # Run this when you want to see the "current" version
time.sleep(0.1) # Use this to pause between steps if the snake is too fast
For this step, you might need to check if a certain item is in a list. Here’s how:
secret_numbers = [5, 28, 97]
guess = 28
if guess in secret_numbers:
print(“You guessed one of my secret numbers!”)
When the snake gets the food, your score should go up, the snake should get longer, and a new food should appear somewhere at random.
To place the food randomly, you need to be able to get random numbers.
The function you need is called "randint". Google "Python randint" to see how to use it.