Комбинация модулей Pygame и Keyboard, крутой обрыв цикла True - PullRequest
0 голосов
/ 30 мая 2019

Я делаю код, который перемещает 0 вверх, вниз, влево и вправо, используя клавиши WASD и модуль клавиатуры для python!

Я не уверен, что делать, и я еще ничего не пробовал...

Это код!

import pygame
from pygame.locals import *
import keyboard;

def draw():
    pygame.init();
    x=1280
    y=720
    screen=pygame.display.set_mode((x, y))
    font = pygame.font.Font('freesansbold.ttf', 24)
    black=(0, 0, 0)
    white=(255, 255, 255)
    text = font.render('0', True, black, white)
    textRect = text.get_rect()
    x=x/2; y=y/2;
    textRect.center=(x, y)
    screen.fill((white))
    screen.blit(text, textRect)


    while True:
        if keyboard.is_pressed('w'):
            textRect = text.get_rect()
            y = y - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)

        if keyboard.is_pressed('a'):
            textRect = text.get_rect()
            x = x - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('d'):
            textRect = text.get_rect()
            x = x + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('s'):
            textRect = text.get_rect()
            y = y + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit();
                quit();
            pygame.display.update()

if __name__=="__main__":
    draw()

Это ошибка

Вот изображение изошибка ( У меня еще нет репутации, чтобы загрузить ее здесь! )

ссылка на GIF: https://gfycat.com/GlossyCheerfulEstuarinecrocodile

ФактическийРезультатом должно быть движение нуля вверх ...

1 Ответ

0 голосов
/ 30 мая 2019

По указанной вами ссылке я не обнаружил ошибок: просто белый экран с буквой О в центре и мигающими маленькими окнами с таким маленьким текстом, что их невозможно прочитать.

Когда я пытался запустить ваш код, ошибка была:

Hello from the pygame community. https://www.pygame.org/contribute.html
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/__init__.py", line 292, in listen
    _os_keyboard.listen(self.direct_callback)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/_darwinkeyboard.py", line 430, in listen
    raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator

Итак, я запустил его как администратор с помощью 'sudo' и смог переместить ноль '0' с помощью клавиатуры.

sudo python3.7 object_type.py
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...