请用python写一个完整的可以跑起来的贪食蛇小游戏
时间: 2023-02-23 15:14:00 浏览: 57
贪食蛇_C++_wild73t_小游戏_贪食蛇小程序_
好的,这是一个 Python 实现的简单的贪吃蛇小游戏:
```
import turtle
import time
import random
delay = 0.1
# Set up the screen
win = turtle.Screen()
win.title("贪吃蛇")
win.bgcolor("lightgreen")
win.setup(width=600, height=600)
win.tracer(0) # Turns off the screen updates
# Create a snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Create food for the snake
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
# Create the snake's body segments
segments = []
# 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)
# Change the snake's direction
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
# Listen for key presses
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_left, "Left")
win.onkeypress(go_right, "Right")
# Main game loop
while True:
win.update()
# Check for collision with the food
if head.distance(food) < 20:
# Move the food to a random location
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# Add a body segment
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()
阅读全文