我正在制作一个基于文本的游戏作为练习,我想告诉用户,当出现无限闪烁的文本时,他们可以输入一些内容。
from time import sleep
print("When this signs happear: ")
user_answer()
sleep(2.3)
print("it means you can input something.")
user_input = input()
def user_answer():
while 1:
print("\r< ", end=""), sleep(1.1)
print("\r> ", end=""), sleep(1.1)
continue
我尝试使用
break
而不是 continue
但问题仍然存在:
当显示闪烁的文本时,它是无限,但代码停止前进,这意味着该行
print("it means you can input something.")
没有出现。
def user_answer():
while 1:
print("\r< ", end=""), sleep(1.1)
print("\r> ", end=""), sleep(1.1)
continue
由于您使用无限循环,因此您的代码将陷入无限循环。 如果我理解正确的话,你希望循环是无限的,直到用户输入一些内容
为此,您需要在所谓的线程内启动“无限循环功能”。
线程将启动您的函数,而主线程(您的应用程序)将继续。
一旦用户输入,你想要求线程打印停止
示例:
from time import sleep
import threading
def user_answer(stop_event):
while not stop_event.is_set():
print("\r< ", end=""), sleep(1.1)
print("\r> ", end=""), sleep(1.1)
print("When this signs appear: ")
stop_event = threading.Event() # to tell when the thread stops
th = threading.Thread(target=user_answer, args=(stop_event,))
th.start()
print("it means you can input something.")
user_input = input()
if user_input:
stop_event.set()
th.join() # Wait for the thread to stop
# continue your code
另一种解决方案可能是删除 while 循环并放入 for 循环 例如:
import termcolor
import time, os
os.system("cls") #clearing
a=["white"]
for b in a:
termcolor.cprint(""*5 "\t\" + "[your flashy text]", b)
time.sleep(1)
os.system("cls") #will clear the above after sleep
#continue your code