3

I'm trying to detect a key press to determine whether the user wants to play again, but msvcrt.getch() is just not working for me. This is my code:

import msvcrt
#the game here
    print "Do you want to continue? Y/N"
    if msvcrt.getch() == 'Y' or msvcrt.getch() == 'y':
        print"Let's play again!"
        print"-----------------"
    elif msvcrt.getch() == 'N' or msvcrt.getch() == 'n' :
        "Okay, hope you had fun"
        break

Any suggestions?

EDIT: The answers below do work on the command line, for some reason just don't in PyCharm

sOfekS
  • 85
  • 6
  • Do you have any errors when you run your code? – cosinepenguin Sep 14 '17 at 17:37
  • You need to call `getch()` __once__, then compare that value four times. As it is, you're only comparing the user's initial keypress against `Y`, then requesting a second keypress.. – jasonharper Sep 14 '17 at 17:39
  • @cosinepenguin @jasonharper No errors, just doesn't register any key press, as if `getch()` doesn't even get called for some reason. – sOfekS Sep 14 '17 at 20:47

1 Answers1

0

You should only call msvcrt.getch() once. Change your code to something like this:

import msvcrt
#the game here
    print "Do you want to continue? Y/N"
    response = msvcrt.getch()
    if response.lower() == 'y':
        print"Let's play again!"
        print"-----------------"
    elif response.lower == 'n' :
        "Okay, hope you had fun"
        break
  • Yeah that makes sense, but it it still doesn't work. Just doesn't seem to register the key press for some reason. – sOfekS Sep 14 '17 at 20:47