gpt4 book ai didi

python - 如何在Python中单独更新 turtle

转载 作者:行者123 更新时间:2023-12-01 07:56:27 25 4
gpt4 key购买 nike

我目前正在尝试在 python 中单独更新多个 turtle 。在下面显示的示例中,我尝试让底部 turtle 移动并根据玩家输入不断更新,而顶部 turtle 向前和向后移动并根据一定的间隔进行更新。

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: 循环,而应该使用计时器事件。下面是修复这些问题的代码的重写。由于您从未为两只 turtle 设置 Y 坐标,因此没有“顶部”或“底部”,只有两只 turtle 彼此移动:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com