简体   繁体   中英

How do I stop user input until I need it?

This game can be cheated by pressing enter or entering any input before an enemy appears. Is there a way to pause user input until it is necessary so that this code works properly?

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

As far as I know there's no way to do this. User input (at least in Unix-like OSes) is read just like a file would, and if a user types things before you read them, they'll just get "queued up" for your program to process later on.

The most common solution games use is multithreading, where you have one thread reading the user's input (and ignoring anything they type while your program doesn't expect it), and another doing the main game loop. Keep in mind this is way more complex than your simple program and brings a whole different host of issues related to concurrency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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