Keyboard input freezes when working with keyboard/mouse input libraries

I'm trying to make Anti-AFK in Minecraft, the essence is that when you press F7, Anti-AFK is turned on and the character runs around the square, but it is also necessary that the keyboard input is not blocked and when Anti-AFK is started, the player can also control the character. But when I turn on Anti-AFK, the character runs around the square, but if you try to control it somehow, there is no control, or the action (for example, pressing the space bar) freezes and the character continues to run with a jump. Please tell me how this can be fixed?

import pyautogui
import pydirectinput # тоже библиотека для управления клавиатурой и мышью.
from pynput import keyboard


class Main:
    def __init__(self):
        self.collect_events()

    def collect_events(self):
        with keyboard.Listener(on_release=self.check_pressed_button) as k_listener:
            k_listener.join()

    def check_pressed_button(self, key):
        if key == keyboard.Key.f7:
            print('Anti-AFK is starting')
            for global_repeat in range(12):
                for local_repeat in range(4):
                    pydirectinput.keyDown('w')
                    pyautogui.moveRel(-782, 0)
            pydirectinput.keyUp('w')
            print('Anti-AFK is ending')


obj = Main()
Author: GunTHE, 2020-10-19

1 answers

Is it necessary to use such an algorithm as you have? I managed to solve the problem by using the library keyboard (pip install keyboard) and Documentation.

In the loop while True there is exactly the same waiting for pressing the key F7, after pressing the algorithm starts and works without the problems you specified. After execution, the loop is expected to press F7{[8 again]}

import pyautogui
import keyboard

while True:
    keyboard.wait('f7')
    print('Anti-AFK is starting')
    for global_repeat in range(12):
        for local_repeat in range(4):
            pyautogui.keyDown('w')
            pyautogui.moveRel(-782, 0)
    pydirectinput.keyUp('w')
    print('Anti-AFK is ending')

As for the mouse, the situation is different here. Mouse also it is controlled by the library, but when you try to use it, there will not be such a feeling of control on the part of the user, as with the keyboard. The simplest thing you can do is to implement running across the square completely through the keyboard, that is, the "WASD" keys.

 1
Author: denisnumb, 2020-10-20 18:17:41