snake/main.py

139 lines
3.2 KiB
Python
Raw Normal View History

import turtle
import random
import time
# 设置屏幕
screen = turtle.Screen()
screen.title("贪吃蛇小游戏")
screen.bgcolor("lightgreen")
screen.setup(width=600, height=600)
screen.tracer(0) # 关闭自动刷新
# 创建蛇头
head = turtle.Turtle()
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 创建食物
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(100, 100)
# 创建蛇的身体
segments = []
# 设置得分
score = 0
high_score = 0
# 记分板
pen = turtle.Turtle()
pen.hideturtle()
pen.penup()
pen.goto(0, 260)
pen.write("得分: 0 最高得分: 0", align="center", font=("Arial", 18, "normal"))
# 控制方向的函数
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":
head.sety(head.ycor() + 20)
if head.direction == "down":
head.sety(head.ycor() - 20)
if head.direction == "left":
head.setx(head.xcor() - 20)
if head.direction == "right":
head.setx(head.xcor() + 20)
# 键盘绑定
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
screen.onkey(go_right, "Right")
# 主游戏循环
while True:
screen.update()
# 碰撞边界
if abs(head.xcor()) > 290 or abs(head.ycor()) > 290:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
score = 0
pen.clear()
pen.write(f"得分: {score} 最高得分: {high_score}", align="center", font=("Arial", 18, "normal"))
# 吃到食物
if head.distance(food) < 20:
# 随机移动食物
x = random.randint(-14, 14) * 20
y = random.randint(-14, 14) * 20
food.goto(x, y)
# 增加身体
new_segment = turtle.Turtle()
new_segment.shape("square")
new_segment.color("gray")
new_segment.penup()
segments.append(new_segment)
# 更新分数
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write(f"得分: {score} 最高得分: {high_score}", align="center", font=("Arial", 18, "normal"))
# 移动身体部分
for i in range(len(segments) - 1, 0, -1):
x = segments[i - 1].xcor()
y = segments[i - 1].ycor()
segments[i].goto(x, y)
if segments:
segments[0].goto(head.xcor(), head.ycor())
move()
# 蛇碰到自己
for segment in segments:
if head.distance(segment) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
score = 0
pen.clear()
pen.write(f"得分: {score} 最高得分: {high_score}", align="center", font=("Arial", 18, "normal"))
time.sleep(0.1)