我目前正在尝试在python中单独更新多只海龟。在下面显示的示例中,我尝试让底部乌龟移动,并根据玩家的输入不断更新,而顶部乌龟向前和向后移动,并根据特定间隔进行更新。
import turtle
from time import sleep
from turtle import Screen, Turtle
screen = turtle.Screen()
screen.title("Turtle Test")
screen.bgcolor("grey")
screen.setup(width=630, height=630)
screen.tracer(0)
turtle_a = turtle.Turtle()
turtle_a.speed(0)
turtle_a.shape("square")
turtle_a.color("white")
turtle_a.penup()
turtle_b = turtle.Turtle()
turtle_b.speed(0)
turtle_b.shape("square")
turtle_b.color("black")
turtle_b.penup()
turtle_b_speed = 10
def go_left():
x = turtle_b.xcor()
x -= turtle_b_speed
turtle_b.setx(x)
def go_right():
x = turtle_b.xcor()
x += turtle_b_speed
turtle_b.setx(x)
screen.listen()
screen.onkeypress(go_left, "Left")
screen.onkeypress(go_right, "Right")
direct = 5
while True:
turtle_a.goto(turtle_a.xcor() + direct, turtle_a.ycor())
sleep(0.5)
if turtle_a.xcor() >= 310:
direct = -5
if turtle_a.xcor() <= -310:
direct = 5
# update function
最佳答案
您知道两次导入turtle时已经走错了路,两种不同的方式,以及在基于事件的环境(例如turtle)中使用sleep()
:
import turtle
from time import sleep
from turtle import Screen, Turtle
您也不应在基于事件的环境中使用
while True:
循环,而应使用计时器事件。下面是对代码的重写,以解决这些问题。由于您从未为这两只乌龟设置Y坐标,因此没有“顶部”或“底部”,只有两只乌龟互相移动:from turtle import Screen, Turtle
def go_left():
x = turtle_b.xcor() - turtle_b_speed
if -300 <= x <= 300:
turtle_b.setx(x)
def go_right():
x = turtle_b.xcor() + turtle_b_speed
if -300 <= x <= 300:
turtle_b.setx(x)
def move_a():
global turtle_a_direct
turtle_a.setx(turtle_a.xcor() + turtle_a_direct)
if not -300 <= turtle_a.xcor() <= 300:
turtle_a.undo()
turtle_a_direct *= -1
screen.ontimer(move_a, 500)
screen = Screen()
screen.title("Turtle Test")
screen.bgcolor('grey')
screen.setup(width=640, height=640)
turtle_a = Turtle('square')
turtle_a.speed('fastest')
turtle_a.color('white')
turtle_a.penup()
turtle_a_direct = 5
turtle_b = Turtle('square')
turtle_b.speed(0)
turtle_b.color('black')
turtle_b.penup()
turtle_b_speed = 10
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()
move_a()
screen.mainloop()
由于您调用了
onkeypress()
,因此我假设使用Python 3。关于python - 如何在Python中单独更新 turtle ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55952490/