如何使一些东西不受影响时间。睡觉()Python

2024-06-28 19:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序分为两个功能。一旦得到一堆弹跳球的数据、位置和颜色。另一个拉这些球,让它们移动。我要做的是每五秒钟出现一个球。为了做到这一点,我必须使用时间。睡觉()一个是data()函数,而不是moving()函数。因为这两者联系如此紧密,我不知道该怎么做。我认为唯一的方法是要么完全改变程序的逻辑(我不想这样做),要么让moving()函数不受影响时间。睡觉()不知怎么的。有什么想法吗?在

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()函数的一部分:

^{pr2}$

Tags: 函数infor时间rangerandomrandintmoving
2条回答

与其在两个球之间使用time.sleep(),为什么不记录所用的时间呢?在

start = time.time()
INTERVAL = 5
while True:
    if time.time() >= start + INTERVAL:
        # release new ball
        start = time.time()
    # deal with movements

或者,您必须使用^{}或{a2}分隔函数。在

您可以使用线程库来执行此操作。例如,您可以在这里看到一个使用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"

这样做的目的是让单个线程休眠,而不是让整个程序休眠。在

相关问题 更多 >