如何让多只乌龟同时在一条线上移动

How to make multiple turtles move in a line at the same time

我的目标是能够让一条蛇(三只彼此相邻的乌龟)同时移动,并使用箭头键让蛇转动。我试过 ontimer method/function 但它没有按预期工作。这是我的代码:

import make_snake
from turtle import Turtle, Screen

game_is_on = True

screen = Screen()
screen.setup(600, 600)
screen.bgcolor("black")
screen.title("Snake Game")

snake_seg1 = make_snake.snake_segments[0]
snake_seg2 = make_snake.snake_segments[1]
snake_seg2.setheading(snake_seg1.heading())
snake_seg3 = make_snake.snake_segments[2]
snake_seg3.setheading(snake_seg2.heading())

def move_forward():
    snake_seg1.forward(20)

def move_backward():
    snake_seg1.backward(20)

def turn_left():
    snake_seg1.left(90)

def turn_right():
    snake_seg1.right(90)

screen.onkey(move_forward, "Up")
screen.onkey(move_backward, "Down")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")

while game_is_on:
    for seg in make_snake.snake_segments:
        seg.forward(20)

    # def follow_head():    
        # snake_seg1.forward(20)
        # snake_seg2.setheading(snake_seg1.heading())
        # snake_seg2.forward(20)
        # snake_seg3.setheading(snake_seg2.heading())
        # snake_seg3.forward(20)
        # screen.ontimer(follow_head, 0)

screen.exitonclick()

文件make_snake:

from turtle import Turtle

start_positions = [0, 20, 40]
snake_segments = []

for position in start_positions:
    snake_part = Turtle(shape="square")
    snake_part.color("white")
    snake_part.penup()
    snake_part.backward(position)
    snake_segments.append(snake_part)

我可以在我的代码中修复什么以使其停止一次移动一只乌龟?

您可能在这里寻找的东西称为多处理。在 Python 中有一个同名库可以同时执行多行代码。作为参考,请查看以下线程: Python: Executing multiple functions simultaneously

您的程序至少有一个问题:您使用 onkey() 但忘记调用 listen() 以允许按键事件。

这里是对您的代码进行的极简返工,以实现基本的蛇形运动,它只支持左右转弯:

from turtle import Turtle, Screen

SEGMENT_SIZE = 20

START_COORDINATES = [-SEGMENT_SIZE * count for count in range(5)]

def turn_left():
    snake_segments[0].left(90)
    screen.update()

def turn_right():
    snake_segments[0].right(90)
    screen.update()

def move_forward():
    for index in range(len(snake_segments) - 1, 0, -1):
        snake_segments[index].goto(snake_segments[index - 1].position())

    snake_segments[0].forward(SEGMENT_SIZE)
    screen.update()
    screen.ontimer(move_forward, 250)

screen = Screen()
screen.setup(600, 600)
screen.title("Snake Game")
screen.tracer(False)

snake_segments = []

for position in START_COORDINATES:
    snake_segment = Turtle(shape='circle', visible=False)
    snake_segment.penup()
    snake_segment.setx(position)
    snake_segment.showturtle()

    snake_segments.append(snake_segment)

snake_segments[0].color('red')

screen.onkey(turn_left, 'Left')
screen.onkey(turn_right, 'Right')
screen.listen()
screen.update()

move_forward()

screen.exitonclick()

小心,蛇很容易从 window 的边缘丢失并且再也找不回来了!