2017-08-16 99 views
1

我寫了下面的代碼,它在兩個隨機位置創建擴展正方形。我想寫一個函數f(方塊,秒),這樣如果用戶輸入f(5,10),一個新的正方形將開始形成每10秒,直到5個形成。難以計時烏龜運動

我似乎無法找到任何東西讓我開始一個新的廣場,而一個仍在形成。我可以同時製作兩種形式,如下面的代碼,或者完成一個,然後再另一個形成。幫幫我?

import sys 
sys.setExecutionLimit(1000000) 
import turtle 
import random 
wn = turtle.Screen() 
#Creates alex the turtle 
alex = turtle.Turtle() 
alex.color('blue') 
alex.pensize(3) 
alex.ht() 
alex.penup() 
#creates bob the turtle 
bob = turtle.Turtle() 
bob.color('blue') 
bob.pensize(3) 
bob.ht() 
bob.penup() 

#Sets variables so that alex starts in a random location 
a=random.randrange(360) 
b=random.randrange(360) 
x=random.randrange(50,150) 
y=random.randrange(50,150) 
#Sets variables so that bob starts in a random location 
l=random.randrange(360) 
m=random.randrange(360) 
n=random.randrange(50,150) 
o=random.randrange(50,150) 
#Moves alex to his random starting location 
alex.speed(100) 
alex.left(a) 
alex.forward(x) 
alex.left(b) 
alex.forward(y) 
alex.pendown() 
#Moves bob to his random starting location 
bob.speed(100) 
bob.left(l) 
bob.forward(n) 
bob.left(m) 
bob.forward(o) 
bob.pendown() 

#Draws the 2 squares 
for i in range(1,500): 
    alex.forward(i) 
    alex.left(90) 
    bob.forward(i) 
    bob.left(90) 

回答

1

您需要的功能需要獨立的執行線程。你需要用多線程工作packagetutorial

你會想邏輯像這樣:

import time 
import threading 

def draw_square(): 
    # Draw a square in a random place 
    length = random.randrange(360) 
    width = random.randrange(360) 
    x_pos = random.randrange(50,150) 
    y_pos = random.randrange(50,150) 

    # Continue with your square-drawing logic; 
    # you already know how to do this. 

while True: 
    threading.thread(draw_square) 
    time.sleep(10)