如何在python中同时移动多只海龟? [英] How to move multiple turtles at the same time in python?

查看:55
本文介绍了如何在python中同时移动多只海龟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项任务,要求在赛道上设置两只海龟(大小相同但不同的赛道).我可以让它们移动,但只有当第一个移动轨道的一半时,第二个才会移动.我不知道如何让海龟同时移动.这是我的代码,如果您有任何想法,请帮助我.谢谢!

Hi I have an assignment which is asked to set two turtles in a race track(same size but separate track). I can able to make them move but the second one move only when the first one moved a half of the track. I'm not sure how to make the turtles move at the same time. Here is my code, please help me if you have any idea about it. Thank you!

import turtle
import random
import time


wn = turtle.Screen()
wn.bgcolor("lightgreen")

t = turtle.Turtle()
t.shape('turtle')
t.color('red')

t2 = turtle.Turtle()
t2.shape('turtle')
t2.color('blue')

#user input function

p = float(input('please insert the perimeter:'))

#set the track
def drawTrack(p,r):
    shortside = (p/2.0)/(r+1)
    longside = r*shortside
    turtle.setup((shortside*2)+60, longside +40)
    t.penup()
    t2.penup()
    t.setposition(-shortside-10, -longside/2)
    t2.setposition(10, -longside/2)   
    for i in range (2):
        #first track
        t.speed(1)
        t.pendown()
        t.forward(shortside)
        t.left(90)
        t.forward(longside)
        t.left(90)

        #second track
        t2.speed(1)
        t2.pendown()
        t2.forward(shortside)
        t2.left(90)
        t2.forward(longside)
        t2.left(90) 

drawTrack(p,2)

wn.exitonclick()

推荐答案

我让每个海龟重复移动一个微小的增量,因此它们之间的距离最大为 1 个像素:

I make the turtles each move a tiny increment repetitively so they only ever are at max 1 pixel apart:

# Setup 
import turtle

screen = turtle.Screen()
screen.bgcolor("white")
screen.title("Turtle Movement")
screen.setup(width=500, height=500)

# Object 1 set up
obj1 = turtle.Turtle()
obj1.color("red") # Sets obj1's colour
obj1.speed(0) # The drawing speed will go as fast as it can if it is set to zero
obj1.penup() # Don't want it to draw a line as I goes to 0, -50
obj1.goto(0, -50) # goes to 0, -50
obj1.pendown() # Now we want it to draw

# Object 2 set up
obj2 = turtle.Turtle()
obj2.color("blue") # sets obj2's colour
obj2.speed(0) # The drawing speed will go as fast as it can if it is set to zero
obj2.penup() # Don't want it to draw a line as I goes to 0, -50
obj2.goto(0, 50) # goes to 0, 50
obj2.pendown() # Now we want it to draw

# Movement of objects
while True: # infinite loop
    obj1.forward(1) # Moves obj1 forwards by 1
    obj2.forward(1) # Moves obj2 forwards by 1

#   Notes
#   -----
#   The smaller the 'Movement amount' is,
#   e.g forward(Movement amount is in here)
#   the smoother the movement gets, but you will lose speed.
#   I encourage you to tweak the values and experiment!



希望对你有帮助!

这篇关于如何在python中同时移动多只海龟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆