Pygame window not receiving keyboard events on Mac

女生的网名这么多〃 提交于 2021-02-04 16:16:28

问题


I am running this very simple tutorial on Pygame:

https://www.youtube.com/watch?v=xh4SV3kF-zk

I can't get keyboard events to be recognised by the game window. I have read a number of similar questions about this, but the answers don't seem right for Macs.

I am using miniconda and it might be that I need to quit the virtualenvironment? I don't understand how to do that tho. Or maybe I need to set the focus to my window - but I don't know how to do that either. This must be an issue lots of people are having on Macs running El Capitan. My Mac is too old to upgrade properly to Sierra. Is there a way to get the keyboard input to work?

import pygame

pygame.init()

display_width = 1200
display_height = 800

black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)


gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A Bit Racey')
clock = pygame.time.Clock()

speederImg = pygame.image.load('speeder.png')

def speeder(x, y):
    gameDisplay.blit(speederImg, (x, y))

x = (display_width * 0.4)
y = (display_height * 0.2)

x_change = 0

crashed = False

while not crashed:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    x += x_change

    gameDisplay.fill(white)
    speeder(x, y)
        # print(event)


    pygame.display.update()

    clock.tick(60)

pygame.quit()
quit()

回答1:


For anybody else trying to run from the terminal using Python3 on a Mac, it seems the problem is the window focus. To get it to run properly instead of typing:

python mygame.py

type instead:

pythonw mygame.py

See https://github.com/pygame/pygame/issues/359 for further info



来源:https://stackoverflow.com/questions/47838446/pygame-window-not-receiving-keyboard-events-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!