【问题标题】:How do I stop user input until I need it?如何在需要之前停止用户输入?
【发布时间】:2019-03-26 13:44:58
【问题描述】:

这个游戏可以通过在敌人出现之前按回车或输入任何输入来作弊。 有没有办法暂停用户输入,直到有必要这样代码才能正常工作?

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()

【问题讨论】:

  • 不要尝试在行模式程序中进行实时处理。您使用线模式是因为它很简单,并且任何解决该问题的方法都会很复杂。有时您会意识到,许多在这里难以处理的事情在 GUI 应用程序中自然会得到解决。所以我的建议是:在使用行模式时保持一切简单,只有在将整个东西转换为 GUI 框架时才担心实时处理。
  • 谢谢。我怎样才能让我的代码正常工作?
  • 这能回答你的问题吗? How to flush the input stream in python?

标签: python python-3.x


【解决方案1】:

据我所知,没有办法做到这一点。用户输入(至少在类 Unix 操作系统中)就像文件一样被读取,如果用户在您读取它们之前输入了内容,他们只会“排队”供您的程序稍后处理。

游戏使用最常见的解决方案是多线程,其中一个线程读取用户的输入(并在您的程序没有预料到的情况下忽略他们键入的任何内容),另一个执行主游戏循环。请记住,这比您的简单程序要复杂得多,并且会带来与并发相关的一系列完全不同的问题。

【讨论】:

  • 感谢您的回答。你能告诉我如何编辑我的代码以使其工作吗?
  • 正如我所提到的,它实际上变得相当复杂,您可以查看gameprogrammingpatterns.com/game-loop.html 之类的资源,与您当前的代码没什么关系,只需重写它。
猜你喜欢
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多