1

I'm currently building a python code to play Blackjack where I need to be able to call certain functions uppon keypress without necessarily being in the terminal. I found this keyboard module which helped but I came across this issue.

def hit_or_stand(deck,hand):
    global playing
    print ("\nWould you like to Hit or Stand? Enter 'h' or 's'")

    if keyboard.is_pressed('h'):
        hit(deck,hand)  

    if keyboard.is_pressed('s'):
        print("Player stands. Dealer is playing.")
        playing = False

Let me explain what this function does as I don't want to overload everyone with the entire code. Essentially this function is called in a loop until the player decides to hit s which declares playing as False and therefore stopping the loop. If the player hits h then the hit function is called which draws a card. The player can draw as many cards.

My problem right now is that this code doesn't wait for user keypress. It loops extremely fast repeating it. I only want it to loop after either h or s is pressed.

I tried using keyboard.wait('h') on the line above the first if but then this doesn't allow the user to press s and therefore declare playing as False.

What I'm looking for is something along the lines of keyboard.wait('h'or's') but I know this does not work.

Thank you for your help. I am using python 3.7.9

EDIT: Keyboard Module I am referring too: https://pypi.org/project/keyboard/

Cruxer
  • 21
  • 6

2 Answers2

1

Use keyboard.read_key() to wait for any input.

If it's not h or s ,read_key again.

Kahn
  • 206
  • 1
  • 7
0
import keyboard

def mywait():
    keyboard.read_key()

def my_function():
    print("Hello")

def my_exit():
    quit()

keyboard.add_hotkey("p", my_function)
keyboard.add_hotkey("esc", my_exit)

while True:
    mywait()
mustafa candan
  • 567
  • 5
  • 16
  • `raise ImportError('You must be root to use this library on linux.') ImportError: You must be root to use this library on linux.` – jaromrax Nov 08 '22 at 12:23