这个游戏可以通过按enter键或在敌人出现之前输入任何输入来作弊。有没有办法暂停用户输入,直到它是必要的,以便这段代码正常工作?
import random
import os
hp = 20
Shp = str(hp)
score = 0
def shoot():
hp = 20
score = 0
while hp > 0:
wait = random.randint(1, 7)
time.sleep(wait)
os.system("clear")
print("An Enemy!")
now = time.time()
hit = input("")
if time.time() - now < 0.4:
print("You hit them!")
score = score+1
time.sleep(1)
os.system('clear')
else:
print("They hit you first.")
hp = hp-5
time.sleep(1)
os.system('clear')
print("Game over. You scored", score)
print("When an enemy appears, press ENTER to shoot.\n You start with "+Shp+"HP, if the enemy hits you before you hit them, you lose HP.\n\n Press ENTER to begin.")
start = input("")
os.system('clear')
shoot()发布于 2019-03-26 21:59:56
据我所知,没有办法做到这一点。用户输入(至少在类Unix的OSes中)就像文件一样被读取,如果用户在您读取它们之前输入内容,那么它们将被“排队”,等待您的程序稍后处理。
游戏使用的最常见的解决方案是多线程,其中一个线程读取用户的输入(并忽略他们输入的任何内容,而您的程序并不期望它),另一个线程执行主游戏循环。请记住,这比你的简单程序要复杂得多,并且带来了完全不同的与并发相关的问题。
https://stackoverflow.com/questions/55358679
复制相似问题