Можно ли заставить модуль клавиатуры работать с pygame и threading - PullRequest
3 голосов
/ 06 января 2020

Мой друг предложил мне создать небольшую программу, которая позволит пользователю нажимать кнопку на контроллере Xbox и выполнять несколько функций на клавиатуре (например, reWASD). Я думал, что я почти дошел до конца и обнаружил, что наличие keyboard.press () и keyboard.release () не будет выполнять свою функцию. Есть ли какой-нибудь возможный способ заставить его делать то, на что я надеялся? Извините за плохой Engli sh Я новичок и его 1 утра, и я новичок в Stakoverflow форматирования.

Вот мой код.

import keyboard  # using module keyboard
import pygame
import threading
pygame.init()
pygame.joystick.init()
clock = pygame.time.Clock()

BLACK = pygame.Color('black')
WHITE = pygame.Color('white')
stall = 0

def stall1():
    global stall
    while stall == 1:
        keyboard.press('a')
        keyboard.release('a')
        stall = 0



# This is a simple class that will help us print to the screen.
# It has nothing to do with the joysticks, just outputting the
# information.
class TextPrint(object):
    def __init__(self):
        self.reset()
        self.font = pygame.font.Font(None, 20)

    def tprint(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, (self.x, self.y))
        self.y += self.line_height

    def reset(self):
        self.x = 10
        self.y = 10
        self.line_height = 15

    def indent(self):
        self.x += 10

    def unindent(self):
        self.x -= 10

screen = pygame.display.set_mode((500, 700))

pygame.display.set_caption("My Game")

textPrint = TextPrint()


while True:  # making a loo
    t = threading.Thread(target=stall1())

    screen.fill(WHITE)
    textPrint.reset()

    # Get count of joysticks.
    joystick_count = pygame.joystick.get_count()

    textPrint.tprint(screen, "Number of joysticks: {}".format(joystick_count))
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.JOYBUTTONDOWN:
            print("Button Pressed")
            if joystick.get_button(0):
                stall = 1
            # Control Left Motor using L2
            elif joystick.get_button(2):
                # Control Right Motor using R2
                print('yote')
        elif event.type == pygame.JOYBUTTONUP:
            print("Button Released")

    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()

        # Get the name from the OS for the controller/joystick.
        name = joystick.get_name()

        # Usually axis run in pairs, up/down for one, and left/right for
        # the other.
        axes = joystick.get_numaxes()
    pygame.display.flip()

    # Limit to 20 frames per second.
    clock.tick(20)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

Просто так я могу попытаться объяснить просто. Я хочу нажать кнопку и напечатать что-нибудь. Использование потоков, Pygame и клавиатуры. Извините, я новичок в кодировании и форматировании в stackoverflow.

1 Ответ

3 голосов
/ 06 января 2020

Оператор

t = threading.Thread(target=stall1())

не делает того, что вы ожидаете, потому что stall1() - это вызов функции stall1. Это означает, что функция будет вызвана немедленно в главном потоке, а возвращаемое значение функции будет передано ключевому аргументу target (* в данном случае None).

Вам необходимо передать функцию объект (stall1) с аргументом:

t = threading.Thread(target=stall1)

Измените функцию stall1, чтобы она работала, пока установлено состояние thread_running:

stall = 0
thread_running = True
def stall1():
    global stall
    while thread_running:
        if stall == 1:
            stall = 0
            keyboard.press('a')
            keyboard.release('a')

Start поток и инициализировать джойстик перед основным приложением l oop:

t = threading.Thread(target=stall1)
t.start()

joystick_count = pygame.joystick.get_count()
if joystick_count > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

run = True
while run:

    screen.fill(WHITE)
    textPrint.reset()
    textPrint.tprint(screen, "Number of joysticks: {}".format(joystick_count))

    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
          thread_running = False  
          run = False

        if event.type == pygame.KEYDOWN:
            print(chr(event.key)) # print key (triggered from 'stall1')

        if event.type == pygame.JOYBUTTONDOWN:
            print("Button Pressed")
            if joystick.get_button(0):
                stall = 1
            elif joystick.get_button(2):
                print('yote')
        elif event.type == pygame.JOYBUTTONUP:
            print("Button Released")

    pygame.display.flip()
    clock.tick(20)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...