3

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()
Mordalvil
  • 43
  • 6
  • 1
    Do not try to do real time processing in a line mode program. You use line mode because it is simple and any way to solve that will be complex. At a time you will realize that many things that are hard to process here would be naturally solved in a GUI application. So my advice is: keep everything simple while you use line mode, and only worry for real time processing when you will convert the whole thing to a GUI framework. – Serge Ballesta Mar 26 '19 at 14:51
  • Thank you. How could I make my code work correctly? – Mordalvil Mar 26 '19 at 16:15
  • Does this answer your question? [How to flush the input stream in python?](https://stackoverflow.com/questions/2520893/how-to-flush-the-input-stream-in-python) – Richard Chambers Aug 06 '21 at 03:31

1 Answers1

1

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.

  • Thank you for your answer. Can you show me how to edit my code to make it work? – Mordalvil Mar 26 '19 at 16:14
  • As I mentioned it actually gets pretty complicated, you can check out resources like http://gameprogrammingpatterns.com/game-loop.html, there's not much to do with your current code than to rewrite it. – Lucas Lavandeira Mar 27 '19 at 14:46