用python 写一个 贪吃蛇的游戏
时间: 2024-05-15 07:16:08 浏览: 25
下面是一个简单的 Python 贪吃蛇游戏的示例代码:
```python
import turtle
import time
# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇游戏")
# 设置蛇的初始位置和大小
snake = turtle.Turtle()
snake.shape("square")
snake.color("green")
snake.penup()
snake.goto(0,0)
snake.direction = "stop"
# 设置食物的初始位置和大小
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(100,100)
# 定义移动函数
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"
# 绑定按键
turtle.listen()
turtle.onkey(go_up, "Up")
turtle.onkey(go_down, "Down")
turtle.onkey(go_left, "Left")
turtle.onkey(go_right, "Right")
# 游戏主循环
while True:
turtle.update()
# 判断是否吃到食物
if snake.distance(food) < 20:
x = turtle.xcor()
y = turtle.ycor()
food.goto(x + 20, y + 20)
move()
time.sleep(0.1)
```
这只是一个简单的游戏示例,可能需要进一步添加游戏规则和功能。
这个代码依赖于 turtle 库,在使用之
阅读全文