生成一个python贪吃蛇代码
时间: 2023-11-06 20:49:05 浏览: 107
好的,以下是一个简单的Python贪吃蛇游戏代码:
```python
import turtle
import random
# 设置窗口大小
WIDTH = 500
HEIGHT = 500
turtle.setup(WIDTH, HEIGHT)
# 设置蛇的初始位置和方向
START_X, START_Y = 0, 0
START_DIRECTION = "right"
# 设置食物的初始位置
FOOD_X = random.randint(-WIDTH/2+10, WIDTH/2-10)
FOOD_Y = random.randint(-HEIGHT/2+10, HEIGHT/2-10)
# 创建蛇的头
head = turtle.Turtle()
head.penup()
head.goto(START_X, START_Y)
head.direction = START_DIRECTION
# 创建食物
food = turtle.Turtle()
food.penup()
food.shape("circle")
food.color("red")
food.goto(FOOD_X, FOOD_Y)
# 创建蛇的身体
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"
# 监听键盘事件
turtle.listen()
turtle.onkey(go_up, "Up")
turtle.onkey(go_down, "Down")
turtle.onkey(go_right, "Right")
turtle.onkey(go_left, "Left")
# 设置游戏循环
while True:
turtle.update()
# 判断蛇是否吃到食物
if head.distance(food) < 20:
# 更新食物的位置
FOOD_X = random.randint(-WIDTH/2+10, WIDTH/2-10)
FOOD_Y = random.randint(-HEIGHT/2+10, HEIGHT/2-10)
food.goto(FOOD_X, FOOD_Y)
# 增加蛇的身体
segment = turtle.Turtle()
segment.penup()
segment.shape("square")
segment.color("white")
segments.append(segment)
# 移动蛇的身体
for i in range(len(segments)-1, 0, -1):
x = segments[i-1].xcor()
y = segments[i-1].ycor()
segments[i].goto(x, y)
# 移动蛇的头
move()
# 判断蛇是否撞墙或自己
if head.xcor() > WIDTH/2 or head.xcor() < -WIDTH/2 or head.ycor() > HEIGHT/2 or head.ycor() < -HEIGHT/2:
turtle.goto(0, 0)
turtle.write("Game Over", align="center", font=("Arial", 24, "normal"))
break
for segment in segments:
if segment.distance(head) < 20:
turtle.goto(0, 0)
turtle.write("Game Over", align="center", font=("Arial", 24, "normal"))
break
```
这段代码使用了 Python 自带的 turtle 模块来绘制游戏界面,通过监听键盘事件来改变蛇的方向,使用碰撞检测来判断蛇是否吃到食物或撞墙自杀,实现了一个简单的贪吃蛇游戏。
阅读全文