我的程序分为两个功能。一旦获得一堆弹跳球的数据,位置和颜色。另一个吸引这些球并让它们移动。我要做的是每五秒钟出现一个球。为了做到这一点,我必须在data()函数上使用time.sleep(),而不是move()函数。由于这两者是如此紧密相连,我无法弄清楚如何做到这一点。我认为唯一的方法是完全机会我的程序逻辑(我不想这样做),或者使move()函数不受某种方式影响time.sleep()。有什么想法吗?
getData()函数:
def getData(numobjects):
for x in range(int(numobjects)):
xCoordinate.append(random.randint(-300, 300))
yCoordinate.append(random.randint(-300, 300))
speed1.append(random.randrange(-8,8))
speed2.append(random.randrange(-8,8))
for i in range(len(speed1)):
for char in range(len(speed2)):
if i == 0 or char == 0:
i = random.randint(-8,8)
char = random.randint(-8,8)
color.append([random.random(), random.random(), random.random()])
moving()函数的一部分:
# Clearing the canvas and hiding the turtle for the next iteration of moving()
turtle.clear()
turtle.hideturtle()
# Drawing all of the circles
for i in range(len(xCoordinate)):
turtle.penup()
turtle.goto(xCoordinate[i], yCoordinate[i])
turtle.pendown()
turtle.fillcolor(color[i][0], color[i][1], color[i][2])
turtle.begin_fill()
turtle.circle(15)
turtle.end_fill()
xCoordinate[i] += speed1[i]
yCoordinate[i] += speed2[i]
# Bouncing off edges of the screen
if xCoordinate[i] > 300:
xCoordinate[i] = 299
speed1[i] *= -1
if xCoordinate[i] < -300:
xCoordinate[i] = -299
speed1[i] *= -1
if yCoordinate[i] > 300:
yCoordinate[i] = 299
speed2[i] *= -1
if yCoordinate[i] < -300:
yCoordinate[i] = -299
speed2[i] *= -1
# updating turtle and running the moving() function every ten milliseconds
turtle.update()
turtle.ontimer(moving, 10)
答案 0 :(得分:1)
不是在球之间使用time.sleep()
,为什么不跟踪经过的时间?
start = time.time()
INTERVAL = 5
while True:
if time.time() >= start + INTERVAL:
# release new ball
start = time.time()
# deal with movements
或者,您必须使用multiprocessing
或threading
分隔您的功能。
答案 1 :(得分:-1)
您可以使用线程库来执行此操作。例如,您可以在此处使用time.sleep()
方法查看一个很好的示例:http://www.tutorialspoint.com/python/python_multithreading.htm
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
这个想法是你让个别线程睡眠,而不是整个程序。