python - 用鼠标在python游戏中移动角色的问题
问题描述
我正在 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()
我想要实现的是用鼠标移动我的角色 - 键盘已经可以工作,但我不知道如何在这个游戏中实现鼠标
解决方案
异常告诉您该Event
对象没有key
属性。看看pygame 的文档:
来自系统的事件将具有基于类型的一组有保证的成员属性。以下是事件类型及其特定属性的列表。
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
是 type时MOUSEBUTTONDOWN
,它没有key
属性,但有一个pos
和一个button
属性。
因此,如果要检查是否单击了鼠标左键,请检查event.button == 0
.
当您遇到此类错误时,请使用调试器检查有问题的对象(或使用简单print
的语句)并查找文档。
推荐阅读
- swift - 使用 Swift Network Framework,如何使 IPv4Address 和 IPv6Address 符合 Codable?
- r - 如何绑定两个随机集的行,然后将它们绘制为 dplyr 中的直方图?
- reactjs - 通过选择单元格在警报消息中显示值
- java - 为什么我无法下载任何网站的任何 html 页面?(我使用的是 android studio)
- c++ - 这种用于在连续子数组中找到最大和的递归算法有什么优势吗?
- flutter - 如何在飞镖中查询列表列表?
- c++ - 模板化类如何解决对其一种类型调用的重载非成员函数?
- javascript - solr 过滤和 javascript 过滤
- c# - 使用 await Task.WhenAny() 忽略异常
- lambda - Racket 中是否有返回过程的 lambda 表达式的函数?