运行代码时,我收到以下错误消息。
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/MyDevWork/PygamesRelated/game_1.py", line 29, in <module>
elif event.key == pygame.K_s:
AttributeError: 'Event' object has no attribute 'key'
这是我的代码:
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
FPS = 60
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect.move_ip(0, -2)
elif event.key == pygame.K_s:
rect.move_ip(0, 2)
elif event.key == pygame.K_a:
rect.move_ip(-2, 0)
elif event.key == pygame.K_d:
rect.move_ip(2, 0)
screen.fill(BLACK)
screen.blit(image, rect)
pygame.display.update()
我正在使用python 3.7和Pycharm。
答案 0 :(得分:2)
如上所述,您的缩进是这里的问题。检查event.key
的所有内容都应位于KEYDOWN
检查的“内部”。将while循环更改为:
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect.move_ip(0, -2)
elif event.key == pygame.K_s:
rect.move_ip(0, 2)
elif event.key == pygame.K_a:
rect.move_ip(-2, 0)
elif event.key == pygame.K_d:
rect.move_ip(2, 0)