1.简介
使用了turtle库来创建图形界面,你可以使用键盘的W、A、S、D键来控制蛇的移动方向。蛇吃到食物后,身体会增长,如果蛇撞到自己或者游戏边界,游戏就会结束。
2. 代码
import turtle
import time
import random
delay = 0.1
# 生成食物的位置
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-15, 15), random.randint(-15, 15))
food.speed(0)
# 蛇头
head = turtle.Turtle()
head.shape("square")
head.color("blue")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 蛇的食物
segments = []
# 用于控制蛇的移动
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)
#游戏结束
def game_over():
# 提示游戏结束
print("Game Over")
turtle.write("Game Over", align="center", font=("Courier", 24, "normal"))
head.goto(0, 0)
head.direction = "stop"
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
turtle.done()
# 键盘绑定
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"
# 键盘监听
turtle.listen()
turtle.onkey(go_up, "w")
turtle.onkey(go_down, "s")
turtle.onkey(go_left, "a")
turtle.onkey(go_right, "d")
# 主游戏循环
while True:
turtle.update()
# 检查碰撞边界
if head.xcor()> 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
game_over()
# 检查蛇头是否接触到食物
if head.distance(food) < 20:
# 移动食物到随机位置
x = random.randint(-15, 15)
y = random.randint(-15, 15)
food.goto(x, y)
# 添加蛇的身体段
new_segment = turtle.Turtle()
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()
# 检查蛇头碰到身体
for segment in segments:
if 0 < segment.distance(head) < 20:
game_over()
time.sleep(delay)
turtle.done()