繁体   English   中英

在需要之前如何停止用户输入?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM