[英]How do I stop user input until I need it?
在敵人出現之前按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()
據我所知,沒有辦法做到這一點。 用戶輸入(至少在類Unix操作系統中)就像文件一樣被讀取,如果用戶在讀取它們之前輸入內容,它們就會“排隊”以便稍后處理您的程序。
最常見的解決方案游戲使用多線程,你有一個線程讀取用戶的輸入(並忽略他們在你的程序沒有預料到時輸入的任何東西),另一個做主游戲循環。 請記住,這比簡單程序更復雜,並帶來與並發相關的大量不同問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.