-2

I am designing a game in which I require the input function to accept input without requiring the user to press the enter key. Also,once the user enters a single character,the variable in which the input is supposed to be stored must contain that character at once(as if the user had pressed the enter key after entering that character). The character entered must be displayed on screen only if it satisfies a given condition. Please enlighten me on how I can achieve this. Thank you.

NOTE:I am a beginner in Python, hence please do not delve into things that are way beyond my comprehension.My teacher has forbidden us from using classes for our project. I should be able to utilize the characters displayed on screen which I don't find possible using the solutions given for other similar questions.

Prongs
  • 39
  • 4
  • "I am designing a game" ... with what? What you want might be possibly in f.e. pygame with callback/eventloop but not in "normal" console. There are some modules that allow it - see f.e. this question: https://stackoverflow.com/questions/2408560/python-nonblocking-console-input – Patrick Artner Jan 13 '19 at 13:21
  • 2
    The best thing is to do some research on the topic yourself, find two or three, _analyze_ them, determine if they work for you or not, and _try them out_. Come to us when you have a _specific question_ about something you have attempted to do and provide a [mcve] as well as expected outputs/error stacktrace if it went wrong. Asking for recommendation of libraries/full code is offtopic here. see [ask]. – Patrick Artner Jan 13 '19 at 13:27

1 Answers1

1

After searching, I found a packaged named msvcrt, and it can be helpful in your situation. For more information, please check: raw_input in python without pressing enter.

Following is a simple example(it works in Windows). You should open your command line and use python xxx.py to execute the following program.

import msvcrt
import sys

while True:
    c = msvcrt.getch()
    if c == b'\x03': # Ctrl-C
        sys.exit()
    #print(type(c)) # bytes

    #convert from bytes to str
    c = c.decode('utf-8')

    if c =='a': #replace 'a' with whatever you want
        print(c)

It takes the single character input from msvcrt.getch() and assign it to the variable c.

And it prints that character if its string format equals to 'a'.

If you want to exit the program, just press Ctrl-C.

EDIT:

From Python kbhit() problems, it seems msvcrt.getch cannot work in IDLE by nature. But there is a workaround (adjusted from: PyCharm: msvcrt.kbhit() and msvcrt.getch() not working?). If you are using Spyder, click Run -> Configuration per file -> Execute in an external system terminal. And when you later run the script file, a console window will jump up.

keineahnung2345
  • 2,635
  • 4
  • 13
  • 28
  • thank you mate. It does work on command line, but not on shell. How can I make it work on shell? – Prongs Jan 14 '19 at 11:59