如何在 python turtle 中使 2 个 while 循环同时工作

How to make 2 while loops work at the same time in python turtle

我想让两个方块移动,但是当第一个方块移动到中间时,它停止了。然后,当第一个块位于 (0,0) 时,第二个块开始移动。是否可以让第二个方块和第一个方块都移动但第一个方块先开始?

代码如下:

from turtle import *
import time
import random

screen=Screen()
screen.setup(800,400)
x=0
blockx=500
blockx2=500
t1=Turtle(shape="square")
t1.speed(0)
speed(0)
t2 = Turtle ( shape="square" )
t2.speed ( 0 )
t2.up ( )
t2.goto ( blockx2 , -100 )
t2.down ( )
up ( )
goto (500, -110)
down ( )
goto(-500,-110)

while True:
    t1.up()
    t1.goto(blockx,-100)
    t1.down()
    blockx-=10
    if blockx==-500:
        t1.up ( )
        blockx+=1000
        t1.goto ( blockx , -100 )
        t1.down ( )
    if blockx==0:
        t2.up ( )
        t2.goto(blockx2,-100)
        t2.down()
        t2.shape("square")
        blockx2-=10
        if blockx2==-500:
            t2.up ( )
            blockx2+=1000
            t2.goto ( blockx , -100 )
            t2.down ( )
#! /usr/bin/python3

from turtle import *
import time
import random

screen = Screen()
screen .setup( 800, 400 )

blockx = 500  ##  set start positions,
blockx2 = 600  ##  for both blocks

t1 = Turtle( shape='square' )
t1 .color( 'red' )
t1 .speed( 0 )
t1 .up()

##  t1 & t2 are essentially the same.
##  You can use .clone() here to copy t1's properties, & save typing those same commands again.
t2 = t1 .clone()
t2 .color( 'blue' )

while True:
    blockx -= 10  ##  nudge both positions left
    blockx2 -= 10

    t1 .goto( blockx, -100 )
    t2 .goto( blockx2, -100 )

    if blockx == -500:  ##  if either hit the left side of screen,
        blockx  = 500  ##  then set position back to right side of screen
    if blockx2 == -500:
        blockx2  = 500

我建议使用 ontimer() 事件来更独立地控制您的块:

from turtle import Screen, Turtle

WIDTH, HEIGHT = 800, 400
CURSOR_SIZE = 20
BASELINE = -CURSOR_SIZE/2

def move_block(block):
    block.x -= CURSOR_SIZE/2
    block.setx(block.x)

    if block.x <= CURSOR_SIZE/2 - WIDTH/2:
        block.x += WIDTH + CURSOR_SIZE
        block.setx(block.x)

    screen.update()
    screen.ontimer(lambda: move_block(block), 30)  # delay in milliseconds

screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.tracer(False)

marker = Turtle()
marker.hideturtle()
marker.penup()
marker.goto(WIDTH/2, BASELINE)
marker.pendown()
marker.goto(-WIDTH/2, BASELINE)

block_1 = Turtle(shape="square")
block_1.penup()
block_1.color('red')
block_1.x = WIDTH/2 + CURSOR_SIZE  # user defined property
block_1.setx(block_1.x)

block_2 = block_1.clone()
block_2.color('green')
block_2.x = block_1.x + 125
block_2.setx(block_2.x)

block_3 = block_2.clone()
block_3.color('blue')
block_3.x = block_2.x + 75
block_3.setx(block_3.x)

move_block(block_1)
move_block(block_2)
move_block(block_3)

screen.mainloop()

在您的解决方案中要考虑的一个方面或建议的一个方面是,如果您想再添加一个块,您的代码必须更改多少。