使用turtle库绘制一条蛇python语言
时间: 2023-10-23 19:14:19 浏览: 186
Python如何使用turtle库绘制图形
好的,以下是使用turtle库绘制一条蛇的Python代码:
```python
import turtle
import time
import random
delay = 0.1
# 设置屏幕
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0)
# 蛇的头部
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 蛇的食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
segments = []
# 定义函数
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
elif head.direction == "down":
y = head.ycor()
head.sety(y - 20)
elif head.direction == "right":
x = head.xcor()
head.setx(x + 20)
elif head.direction == "left":
x = head.xcor()
head.setx(x - 20)
# 移动函数
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_right():
if head.direction != "left":
head.direction = "right"
def go_left():
if head.direction != "right":
head.direction = "left"
# 定义键盘绑定
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_right, "d")
wn.onkeypress(go_left, "a")
# 游戏循环
while True:
wn.update()
# 检查碰撞
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"
# 隐藏分段
for segment in segments:
segment.goto(1000, 1000)
# 清空分段列表
segments.clear()
# 检查食物碰撞
if head.distance(food) < 20:
# 食物移动到随机位置
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# 添加新的分段
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# 移动分段
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
# 移动第一个分段到头部
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
move()
# 检查蛇头与分段碰撞
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 隐藏分段
for segment in segments:
segment.goto(1000, 1000)
# 清空分段列表
segments.clear()
time.sleep(delay)
```
运行代码后,将会看到一个绘制了蛇和食物的窗口。通过按键盘上的“w”、“s”、“a”、“d”键,可以控制蛇的移动方向。当蛇头碰到边缘或者碰到自己的身体时,游戏结束。
阅读全文