如何使用Python语言编写贪吃蛇游戏?
以下是使用Python语言结合 turtle 库实现的一个简单贪吃蛇游戏代码示例,仅供参考:
python
import turtle
import time
import random
# 设置游戏窗口
win = turtle.Screen()
win.title("贪吃蛇游戏")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0) # 关闭自动更新画面
# 蛇头
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)
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 == "left":
x = head.xcor()
head.setx(x - 20)
elif head.direction == "right":
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_left():
if head.direction!= "right":
head.direction = "left"
def go_right():
if head.direction!= "left":
head.direction = "right"
# 键盘绑定
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_left, "Left")
win.onkeypress(go_right, "Right")
while True:
win.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(-280, 280)
y = random.randint(-280, 280)
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()
time.sleep(0.1)
win.mainloop()
这段代码创建了一个简单的贪吃蛇游戏界面,通过键盘控制蛇头移动,吃到食物会增长蛇身,碰到边界游戏重新开始等基本功能。你可以根据需求进一步扩展和完善它,比如增加计分功能等。如果使用其他编程语言实现,思路类似但具体代码语法会有所不同。