如何在Python中单独更新海龟

时间:2019-05-02 12:29:17

标签: python turtle-graphics

我目前正在尝试在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

1 个答案:

答案 0 :(得分:1)

您知道两次导入乌龟时已经走错了路,有两种不同的方式,并且在基于事件的环境(例如乌龟)中使用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。