【问题标题】:Problems with moving character in python game with mouse [duplicate]用鼠标在python游戏中移动角色的问题[重复]
【发布时间】:2019-09-25 16:41:27
【问题描述】:

我正在 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()

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

【问题讨论】:

  • 你的错误是什么?尝试添加一些细节
  • 当我使用sn-ps实现鼠标事件时,游戏停止运行。
  • 添加运行代码时看到的错误
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。
  • 再详细一点会很有用

标签: python pygame mouse


【解决方案1】:

异常告诉您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

如您所见,当EventMOUSEBUTTONDOWN 类型时,它没有key 属性,而是posbutton 属性。

所以如果你想检查鼠标左键是否被点击,检查event.button == 0

当您遇到此类错误时,请使用调试器检查有问题的对象(或仅使用 print 语句)并查找文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多