如何解决python - 如何在python中同时使2个while循环工作
我想让两个块移动,但是当第一个块移动到中间时,它停止了。然后当第一个块在 (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()
在您的解决方案中需要考虑或建议的一个方面是,如果您想再添加一个块,您的代码必须更改多少。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。