我有两个文件。一种是带有邪恶赌徒的游戏,另一种是带有加载功能的游戏,可在文本行之间播放。我的目标是用我的加载函数替换time.sleep()函数。第一个文件如下所示:
import random
import time
import test
def game():
string_o = "Opponent "
string_u = "User "
input_n = ""
input_n = input('Care to try your luck?\n')
while input_n == 'yes' or input_n == 'y':
cpu = random.randint(1,6)
user = random.randint(1,6)
time.sleep(0.5)
print('\nGreat!')
time.sleep(0.2)
input_n=input("\nAre you ready?\n")
time.sleep(0.4)
print(string_o , cpu)
#If the gambler's die roll is above three he gets very happy
if cpu > 3:
print('Heh, this looks good')
time.sleep(0.2)
#...but if it's lower he gets very anxious
else:
('Oh, no!')
test.animate()
print(string_u , user)
if cpu < user:
print('Teach me, master')
else:
print('Heh, better luck next time, kid')
time.sleep()
input_n = input('\nDo you want to try again?\n')
print("Heh, didn't think so.\nPlease leave some room for thr big boys")
game()
另一个文件如下:
import itertools
import threading
import time
import sys
done = False
#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\rDone! ')
t = threading.Thread(target=animate)
t.start()
#would like an x here instead that is defined in the other file
time.sleep(1)
done = True
问题在于动画animate()在游戏开始之前就已经播放了。
我还想在主游戏文件中设置加载功能的时间。有可能吗?
答案 0 :(得分:0)
通过将t.start()
放在test.py
中的任何函数之外,导入animate
时,您就在运行test.py
。您应该将t.start()
放在函数内。同样,导入done
时,您的True
标志也被设置为test.py
,并且总是会立即中断for
内的animate
循环。我认为您根本不需要此标志。将您的test.py
更改为:
import itertools
import threading
import time
import sys
#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\rDone! ')
def start():
t = threading.Thread(target=animate)
t.start()
然后在第一个文件中,直接调用test.animate()
,而不是直接调用test.start()
。