video :Python100 Row series - Greedy Snake games _ Bili, Bili (゜-゜)つロ Let me propose a toast to ~-bilibili
original text :https://hzeyuan.cn/
design sketch
It's actually a point , To the right , Down , To the left , Upward , Back to the origin …
# coordinate , length , Color name
def square(x, y, size, name):
import turtle
turtle.up()
turtle.goto(x, y)
turtle.down()
turtle.color(name)
turtle.begin_fill()
for count in range(4):
turtle.forward(size)
turtle.left(90)
turtle.end_fill()
Then we can draw a square .
The body of a snake is actually a list of squares , So let's try to draw multiple squares .
snake = [[0,0],[0,10]]
for body in snake:
square(body[0], body[1], 10, 'black')
x,y For coordinates
(10,0): It means moving to the right
(-10,0): Means you want to move left
(0,10): Represents moving up
(0,-10): Represents moving down
aim = [0, 10]
# Set the direction
def change_direction(x, y):
aim[0] = x
aim[1] = y
This is the idea : We think of the list as a snake , The right side of the snake is on the right , The tail is on the left !
Here is the code
import copy
def snake_move():
head = copy.deepcopy(snake[-1]) # Make a deep copy of the square of the head
head = [head[0] + aim[0], head[1] + aim[1]] # The square of the head , Move in one direction
snake.append(head) # Add this new square to the head of the snake
snake.pop(0) # The tail of a snake , Remove a square
turtle.clear()# Clear the box
# Draw the whole body of the snake again
for body in snake:
square(body[0], body[1], 10, 'black')
turtle.update()# Update animation
turtle.ontimer(snake_move, 300)
turtle.hideturtle()
turtle.tracer(False)
Let's listen to the keys on the keyboard , Use up, down, left and right to control the movement of the snake !
turtle.listen()
turtle.onkey(lambda: change_direction(10, 0), "Right") # Right
turtle.onkey(lambda: change_direction(-10, 0), "Left") # Left
turtle.onkey(lambda: change_direction(0, 10), "Up") # On
turtle.onkey(lambda: change_direction(0, -10), "Down") # Next
First, when a food is eaten , We are in a specified interval , Randomly produce food .
if head == food: # If the snake head eats food , We will not delete the last square of the snake's tail
print("snake The length of ", len(snake))
food[0] = randrange(-15, 15)*10 # Set the food section , Must be 10 Multiple
food[1] = randrange(-15, 15)*10
else:
snake.pop(0) # The tail of a snake , Remove a square
When the snake touches itself or when the snake touches the border , We'll lose !!
# First set an initial value for the screen 500*500
turtle.setup(500, 500)
# Set boundary condition judgment
def inside(head):
return -250 < head[0] < 250 and -250 < head[1] < 250
# Judge while the snake is moving , If there is a collision, we will mark the head in red , End the game .
if head in snake or not inside(head):
print(head)
square(head[0], head[1], 10, 'red')
turtle.update()
So we finished a simple game of snake eating , We can also adjust the speed , Record score , There are more functions , You can add .