首页 > 解决方案 > 用鼠标在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()

我想要实现的是用鼠标移动我的角色 - 键盘已经可以工作,但我不知道如何在这个游戏中实现鼠标

标签: pythonpygamemouse

解决方案


异常告诉您该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的语句)并查找文档。


推荐阅读