NameError: name 'KEYDOWN' is not defined

▼魔方 西西 提交于 2019-12-21 22:21:17

问题


I am new to programming with PyGame and I've made this code:

import sys, pygame
pygame.init()
size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
player1 = pygame.image.load("player1.png")
player1rect = player1.get_rect()
mod_x = mod_y = 0
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_W:
                movex = 2
            if event.key == K_S:
                movex = -2
    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
    screen.fill(black)
    screen.blit(ball, ballrect)
    screen.blit(player1, player1rect)
    pygame.display.flip()

But when I execute my code, I get this error:

File "C:\Users\User\Documents\Pong\pong.py", line 22, in <module>
    elif event.type == KEYDOWN:
NameError: name 'KEYDOWN' is not defined
             ^
SyntaxError: invalid syntax

Please help me. I need it so much, I need an answer quick.


回答1:


KEYDOWN isn't defined in your code. You can add this to the beginning:

from pygame.locals import *

Or you can do this:

elif event.type == pygame.KEYDOWN



回答2:


Use this command while using pygame library

...
elif event.type == pygame.KEYDOWN
...



回答3:


just change this piece, then it should work :)

elif event.type == KEYDOWN: CHANGE TO: elif event.type == pygame.KEYDOWN:



来源:https://stackoverflow.com/questions/17556426/nameerror-name-keydown-is-not-defined

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