应该创建 3 个正方形,为什么不呢?

Should create 3 squares, why isn't it?

应该创建 3 个正方形,不知道为什么不是。它创建了 1 个三角箭头?

import turtle as t
starting_position = [(-40,0),(-20,0),(-0,0)]


class snake:
  def __init__(self):
    self.segments=[]
    self.create_snake()

  def create_snake(self):
      for position in starting_position:
        newsegment=t.Turtle('Square')
        newsegment.color('red')
        newsegment.penup()
        newsegment.goto(position)
        self.segments.append(newsegment) 

  def move(self):
      for seg_num in range(len(self.segments)-1,0,-1):
        new_x= self.segments[seg_num-1].xcor()
        new_y= self.segments[seg_num-1].ycor()
        self.segments[seg_num].goto(new_x,new_y) 
        self.segments[0].forward(20)
  
    
  t.onkey(t.left(45),'Left')
  t.onkey(t.right(45),'Right')

它应该在 3 个点(起始位置)创建 3 个正方形,但它创建了一个三角形,但颜色也不对??

从主文件调用代码:

import turtle as t
from snake import snake
import time

screen= t.Screen()
screen.title('welcome to my game')
screen.bgcolor('white')


game_on = True
screen.listen()
while game_on == True :
  screen.update()
  time.sleep(0.1)


snakelead = snake().create_snake()

除了@PranavHosangadi 关于 while 循环 (+1) 的精彩评论之外,您的代码还有几个问题。你接近 onkey() 是行不通的(它会变成“默认”海龟,而不是你创建的海龟蛇。)你的移动逻辑从你的位置列表中倒退。

下面是对你的两个文件的返工,它将为你提供基本的蛇形向前移动和转向:

snake.py

from turtle import Turtle

starting_positions = [(-0, 0), (-20, 0), (-40, 0)]

class Snake:
    def __init__(self):
        self.segments = []
        self.create_snake()

        head = self.segments[0]
        screen = head.getscreen()

        screen.onkey(lambda: head.left(45), 'Left')
        screen.onkey(lambda: head.right(45), 'Right')

        screen.listen()

    def create_snake(self):
        for position in starting_positions:
            new_segment = Turtle('circle')
            new_segment.color('red')
            new_segment.penup()
            new_segment.goto(position)

            self.segments.append(new_segment)


    def move(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            position = self.segments[seg_num-1].position()

            self.segments[seg_num].goto(position)

        self.segments[0].forward(20)

主文件

from turtle import Screen
from snake import Snake

def move():
    snake.move()

    screen.ontimer(move, 100)

screen = Screen()
screen.title('Welcome to my game')

snake = Snake()

move()

screen.mainloop()

看看上面的内容对你是否有意义。