用python写个贪吃蛇小程序吧
时间: 2023-05-23 20:02:26 浏览: 78
好的,这是一个简单的贪吃蛇小游戏程序的示例:
```python
import turtle
import time
# 设置窗口大小
turtle.setup(width=600, height=600)
# 创建画布
wn = turtle.Screen()
wn.title("贪吃蛇游戏")
# 创建蛇
snake = turtle.Turtle()
snake.shape("square")
snake.color("black")
snake.penup()
# 设置食物
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
# 设置初始方向
snake.direction = "stop"
# 定义移动函数
def move():
if snake.direction == "up":
y = snake.ycor()
snake.sety(y + 20)
if snake.direction == "down":
y = snake.ycor()
snake.sety(y - 20)
if snake.direction == "left":
x = snake.xcor()
snake.setx(x - 20)
if snake.direction == "right":
x = snake.xcor()
snake.setx(x + 20)
# 定义按键响应函数
def go_up():
snake.direction = "up"
def go_down():
snake.direction = "down"
def go_left():
snake.direction = "left"
def go_right():
snake.direction = "right"
# 绑定按键
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
# 设置焦点
wn.listen()
# 游戏循环
while True:
wn.update()
# 判断是否吃到食物
if snake.distance(food) < 20:
x = snake.xcor()
y = snake.ycor()
food.goto(x, y)
# 移动
move()
# 暂停
time.sleep(0.1)
# 结束游戏
wn.mainloop()
```
请注意,这是一个简单的示例,可能需要进一步添加游戏规则、界
阅读全文