I'm working on a programm where I need a user input for selection while not focused on the console window. The method I want to use is with keyboard inputs on the numpad. I've found this library Python keyboard lib to achieve this. My problem here is that it takes very long time for python to register the key press and gives a feel of poor performance. I need to know whether numpad 4 or numpad 6 is pressed for navigation. In the wiki of the lib was mentioned that you shouldn't use:
while True:
if keyboard.is_pressed('space'):
print('space was pressed!')
This will use 100% of your CPU and print the message many times.
So, this is my code:
print("Choose Attacker or Defender operator:")
print(" Attacker Defender")
att_state = False
def_state = False
while True:
if keyboard.read_key() == "4":
clear()
print("->Attacker Defender")
def_state = False
att_state = True
if keyboard.read_key() == "6":
clear()
print(" Attacker ->Defender")
att_state = False
def_state = True
if keyboard.read_key() == "5" and att_state:
clear()
printAllOp(attackers)
break
if keyboard.read_key() == "5" and def_state:
clear()
printAllOp(defenders)
break
selection = 0
while att_state:
if keyboard.read_key() == "4":
if selection > 0:
selection -= 1
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "6":
if selection < 31:
selection += 1
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "2":
if selection < 23:
selection += 7
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "8":
if selection > 6:
selection -= 7
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "5":
clear()
searchOp(attackers, selection, att_source)
att_state = False
break
I've also realized that the performance is different when using if and elif that's why everything is written with ifs for now.