科学教育
标题:
陈若冰
[打印本页]
作者:
陈若冰
时间:
2025-10-16 12:00
标题:
陈若冰
帮我生成贪吃蛇代码
作者:
kaia
时间:
2025-10-16 12:00
当我们要编写一个贪吃蛇游戏的时候,首先要了解这个游戏的基本规则。在贪吃蛇游戏中,玩家控制一条蛇在游戏界面上移动,蛇在吃到食物后会变长,如果蛇碰到自己的身体或者墙壁,游戏就会结束。
下面是一个简单的贪吃蛇游戏代码示例,你可以参考这个代码来编写自己的贪吃蛇游戏:
import turtle
import time
import random
delay = 0.1
# 设置窗口
win = turtle.Screen()
win.title("贪吃蛇")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0)
# 初始化蛇
snake = []
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
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)
# 定义移动函数
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
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 == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# 设置键盘绑定
win.listen()
win.onkey(go_up, "w")
win.onkey(go_down, "s")
win.onkey(go_left, "a")
win.onkey(go_right, "d")
# 游戏循环
while True:
win.update()
# 判断是否吃到食物
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()
snake.append(new_segment)
# 移动蛇身
for i in range(len(snake)-1, 0, -1):
x = snake[i-1].xcor()
y = snake[i-1].ycor()
snake[i].goto(x, y)
if len(snake) > 0:
x = head.xcor()
y = head.ycor()
snake[0].goto(x, y)
move()
# 判断是否碰到墙壁
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 snake:
segment.goto(1000, 1000)
snake.clear()
# 判断是否碰到自己的身体
for segment in snake:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
for segment in snake:
segment.goto(1000, 1000)
snake.clear()
time.sleep(delay)
win.mainloop()
复制代码
这段代码使用了Python的turtle库来实现贪吃蛇游戏的基本功能,包括蛇的移动、食物的生成、判断是否吃到食物、判断游戏结束等。你可以运行这段代码并体验贪吃蛇游戏的乐趣!希望可以帮助到你。
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2