import turtle
import time
import random
# 设置计分
score = 0
high_score = 0
# 设置计分板
def set_scoreboard():
global score
global high_score
pen.clear()
pen.write("Score: {} High: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# 绘制蛇的每一个部分
def draw_snake(snake_positions):
for position in snake_positions:
pen.goto(position)
pen.dot(radius)
# 蛇移动的方向
def move_snake(snake_positions, direction):
# 蛇头的位置依据移动的方向变化
head = list(snake_positions[0])
if direction == "up":
head[1] += radius
elif direction == "down":
head[1] -= radius
elif direction == "left":
head[0] -= radius
elif direction == "right":
head[0] += radius
new_snake_positions = [head] + snake_positions
return new_snake_positions
# 游戏结束的函数
def game_over():
global game_is_on
game_is_on = False
pen.clear()
pen.write("Game Over!", align="center", font=("Courier", 40, "normal"))
# 主函数
def main():
global game_is_on
global radius
global food_position
global score
global high_score
# 设置画笔和计分板
wn = turtle.Screen()
pen = turtle.Turtle()
radius = 20
pen.speed(0)
wn.bgcolor("black")
pen.color("white")
pen.penup()
# 蛇的初始位置
snake_positions = [(0, 0), (-20, 0), (-40, 0)]
direction = "right"
# 食物的随机位置
food_position = random.randint(-15 * radius, 15 * radius), random.randint(-15 * radius, 15 * radius)
food_is_ate = False
# 游戏是否开始
game_is_on = True
# 绘制蛇和食物
draw_snake(snake_positions)
pen.goto(food_position)
pen.dot(radius)
# 监听键盘事件
wn.listen()
wn.onkeypress(lambda x: "Up" if direction != "down" else "", "Up")
wn.onkeypress(lambda x: "Down" if direction != "up" else "", "Down")
wn.onkeypress(lambda x: "Left" if direction != "right" else "", "Left")
wn.onkeypress(lambda x: "Right" if direction != "left" else "", "Right")
# 游戏循环
while game_is_on:
wn.update()
time.sleep(0.1)
# 蛇吃食物
if snake_positions[0][0] - food_position[0] == radius and snake_positions[0][1] - food
评论已关闭