用 python 写贪吃蛇
时间: 2023-10-16 17:05:36 浏览: 105
好的,以下是用 Python 写贪吃蛇的代码示例:
```
import turtle
import time
import random
delay = 0.1
# Set up the screen
window = turtle.Screen()
window.title("Snake Game")
window.bgcolor("green")
window.setup(width=600, height=600)
window.tracer(0)
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
# Snake body
segments = []
# Functions
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 == "right":
x = head.xcor()
head.setx(x + 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
def up():
if head.direction != "down":
head.direction = "up"
def down():
if head.direction != "up":
head.direction = "down"
def right():
if head.direction != "left":
head.direction = "right"
def left():
if head.direction != "right":
head.direction = "left"
# Keyboard bindings
window.listen()
window.onkeypress(up, "Up")
window.onkeypress(down, "Down")
window.onkeypress(right, "Right")
window.onkeypress(left, "Left")
# Main game loop
while True:
window.update()
# Check for collision with the border
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Check for collision with the food
if head.distance(food) < 20:
# Move the food to a random position
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# Add a new 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()
y = segments[index-1].ycor()
segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
# Check for collision with the body
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
time.sleep(delay)
window.mainloop()
```
希望代码能够对你有所帮助!
阅读全文