我正在制作pygame中的“点击”游戏。我可以实现键盘移动,但是我的角色无法由鼠标控制。我收到此错误:
Traceback (most recent call last):
File "/home/grzegorz/Pulpit/Gierka/gierka.py", line 19, in
<module>
class Player(pg.Rect):
File "/home/grzegorz/Pulpit/Gierka/gierka.py", line 34, in Player
if event.key == BUTTON_LEFT:
AttributeError: 'Event' object has no attribute 'key'
这是源代码:
import pygame as pg
from pygame.locals import *
from pynput.mouse import Controller
pg.init()
mouse = Controller()
pg.mouse.set_cursor(*pg.cursors.broken_x)
pg.display.set_caption("White Collar: The Game")
display = pg.display.set_mode((1000, 1000))
pg.init()
character = pg.image.load("hero.png")
background = pg.image.load("obraz1.png")
characterx = 300
charactery = 300
class Player(pg.Rect):
while True:
display.blit(background, (0, 0))
display.blit(character, (characterx, charactery))
for event in pg.event.get():
if event.type == KEYDOWN:
if event.key == K_a:
characterx -= 40
if event.key == K_d:
characterx += 40
if event.key == K_w:
charactery -= 40
if event.key == K_s:
charactery += 40
if event.type == MOUSEBUTTONDOWN:
if event.key == BUTTON_LEFT:
characterx -= 10
charactery -= 10
if event.type == QUIT:
pg.quit()
exit()
pg.display.update()
我想要实现的是用鼠标移动角色-键盘已经可以工作,但是我不知道如何在此游戏中实现鼠标
答案 0 :(得分:0)
该异常告诉您Event
对象没有key
属性。看看pygame's documentation:
来自系统的事件将根据类型具有一组有保证的成员属性。以下是具有特定属性的列表事件类型。
QUIT none ACTIVEEVENT gain, state KEYDOWN key, mod, unicode, scancode KEYUP key, mod MOUSEMOTION pos, rel, buttons MOUSEBUTTONUP pos, button MOUSEBUTTONDOWN pos, button JOYAXISMOTION joy, axis, value JOYBALLMOTION joy, ball, rel JOYHATMOTION joy, hat, value JOYBUTTONUP joy, button JOYBUTTONDOWN joy, button VIDEORESIZE size, w, h VIDEOEXPOSE none USEREVENT code
如您所见,当Event
的类型为MOUSEBUTTONDOWN
时,它没有key
属性,而只有pos
和button
属性。
因此,如果要检查是否单击了鼠标左键,请检查event.button == 0
。
遇到此类错误时,请使用调试器检查有问题的对象(或仅使用print
语句)并查找文档。