0

I have a block at position (0,0). Periodically (say every 1 second) the y-coordinate of the block will randomly get updated by +/-1.

And every time the user also inputs a character (+/-) the x-coordinate will be updated by +/-1 as the user has inputted.

If it was only the x coord, I could create a while loop, that runs into the next iteration when input() gets a value.

But how can I deal with both the periodic update as well as the real time input (which can come at any time?)

Morgoth
  • 4,935
  • 8
  • 40
  • 66
Ind Oubt
  • 151
  • 1
  • 8
  • 1
    If you're asking "how do I poll for keyboard input without blocking indefinitely until the user hits Enter?", [getch](https://docs.python.org/3/library/msvcrt.html#msvcrt.getch) may be an option. – Kevin Aug 14 '17 at 16:52
  • 1
    Possible duplicate of [What's the simplest way of detecting keyboard input in python from the terminal?](https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal) – EsotericVoid Aug 14 '17 at 16:58
  • @Kevin Ive played simple terminal games (like tetris) written in Python where the updates (in the case of tetris, the main shape going down by one unit) happens every `x` second or so, but the shape can be moved sidewards whenever the user inputs a character (using getch I guess). The updates can be done periodically using some time related module. But how to integrate that with the user's inputs? – Ind Oubt Aug 14 '17 at 16:59

1 Answers1

1

Threading is your friend:

import time
from threading import Thread


# This defines the thread that handles console input
class UserInputThread(Thread):
    def __init__ (self):
        Thread.__init__(self)

    # Process user input here:
    def run(self):
        while True:
            text = input("input: ")
            print("You said", text)
            # Exit the thread
            if text == "exit":
                return


console_thread = UserInputThread()
console_thread.start()

while True:
    time.sleep(5)
    print("function")
    # If the thread is dead, the programme will exit when the current iteration of the while loop ends.
    if not console_thread.is_alive():
        break

UserInputThread runs in the background and handles the user input. print("function") could be any logic you need to do in the main thread.

Morgoth
  • 4,935
  • 8
  • 40
  • 66