In the list, I want to write code that moves side by side according to the keyboard a and d keys, but when I execute it, I want to execute it right away when I press the key a and enter it, but what should I enter it. What should I do?
import random
from pynput.keyboard import Key, Listener
myList=['2','4','1','7','5','6','9','3','8','10']
if__name__=='__main__':
rand_index = random.randint(0,9)
myList[rand_index] = '#'
while True:
print(myList)
command=input("command : ")
if command == 'a' or command == 'A':
if not rand_index == 0:
myList[rand_index], myList[rand_index-1] = myList[rand_index-1], myList[rand_index]
rand_index= rand_index-1
elif command=='d' or command=='D':
if not rand_index == 9:
myList[rand_index], myList[rand_index + 1] = myList[rand_index + 1], myList[rand_index]
rand_index = rand_index + 1
elif command=='exit':
break
def on_press(key):
try:
print(type(key.char))
if key.char == 'a'or'A':
print('a pressed')
elif key. char == 'd'or'D':
print('d pressed')
except AttributeError:
print()
def on_release(key):
try:
print(type(key.char))
if key == Key.esc:
return False
elif key.char == 'a' or 'A':
print('a released')
elif key.char == 'd' or 'D':
print('d released')
except AttributeError:
print()
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Why don't you use getch? You can use msvcrt in the window series You can use termios in UNIX/LINUX series.
I modified the below using the source code that you posted. Please refer to it Note: You can check it by opening the cmd instead of the window python idle shell \r is Enter.
Have a nice day
import random
import msvcrt
myList=['2','4','1','7','5','6','9','3','8','10']
if __name__== '__main__':
rand_index = random.randint(0,9)
myList[rand_index] = '#'
_ismoved = 1
while True:
if(_ismoved == 1):
print(myList)
print("command : ")
_ismoved = 0
if msvcrt.kbhit():
command = msvcrt.getwch()
if command == 'a' or command == 'A':
if not rand_index == 0:
myList[rand_index], myList[rand_index-1] = myList[rand_index-1], myList[rand_index]
rand_index= rand_index-1
_ismoved = 1
elif command=='d' or command=='D':
if not rand_index == 9:
myList[rand_index], myList[rand_index + 1] = myList[rand_index + 1], myList[rand_index]
rand_index = rand_index + 1
_ismoved = 1
elif command=='\r':
break
© 2024 OneMinuteCode. All rights reserved.