从输入的末尾删除字符可能不是最好的方法,因为您不太确定将有多少个字符(
取决于数字
).
来自@QualidSai的答案确实清除了终端,但它不会再次显示公式字符串。为了解决这个问题,我将打印的公式字符串作为输入的一部分存储为字符串变量,然后可以在循环时使用它。例如:
import random
import time
import sys
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
question = "%d + %d = " % (a, b)
elif (asmd == 2):
if (a > b):
solve = a - b
question = "%d - %d = " % (a, b)
else:
solve = b - a
question = "%d - %d = " % (b, a)
elif (asmd == 3):
solve = a * d
question = "%d * %d = " % (a, d)
else:
solve = d
c = a * d
question = "%d / %d = " % (c, a)
answer = False
while (solve != int(answer)):
answer = input(question)
sys.stdout.write("\033[F")
sys.stdout.write("\033[K")
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)