请用Python写一个贪吃蛇
时间: 2023-02-24 16:52:46 浏览: 63
当然! 贪吃蛇是一个很好的编程练习,下面是一份用 Python 实现的代码:
```python
import turtle
import time
delay = 0.1
# Set up the screen
wn = turtle.Screen()
wn.title("贪吃蛇")
wn.bgcolor("lightgreen")
wn.setup(width=600, height=600)
# Create the snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Create the food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
# Create a list to keep track of all the segments of the snake
segments = []
# Function to move the snake
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# Function to change the direction of the snake
def go_up():
head.direction = "up"
def go_down():
head.direction = "down"
def go_left():
head.direction = "left"
def go_right():
head.direction = "right"
# Set the keyboard bindings
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
# Main game loop
while True:
wn.update()
# Check for a collision with the food
if head.distance(food) < 20:
# Move the food to a random spot
x = turtle.randint(-290, 290)
y = turtle.randint(-290, 290)
food.goto(x,y)
# Add a segment to the snake
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# Move the end segments first in reverse order
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x,