gpt4 book ai didi

python - NameError:名称 'KEYDOWN' 未定义

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:28 24 4
gpt4 key购买 nike

我是 PyGame 编程的新手,我编写了以下代码:

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()

但是当我执行我的代码时,我得到这个错误:

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

请帮帮我。我非常需要它,我需要一个快速的答案。

最佳答案

KEYDOWN 未在您的代码中定义。您可以将其添加到开头:

from pygame.locals import *

或者你可以这样做:

elif event.type == pygame.KEYDOWN

关于python - NameError:名称 'KEYDOWN' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com