在 Python 中按下鼠标时移动精灵
我正在制作一个乒乓球克隆用于学习目的,并且需要在按下鼠标时让球从屏幕中间移动(当它经过球拍时它会被发送到那里)。我已经尝试过以下代码,但它什么也没做,所以我可能不理解语法。请尽量保持简单,并解释一下,我宁愿没有 50 行代码(我想理解我在这里使用的所有内容)。我认为这就是所有相关的代码,如果不是,抱歉。谢谢。
def middle(self):
"""Restart the ball in the centre, waiting for mouse click. """
# puts ball stationary in the middle of the screen
self.x = games.screen.width/2
self.y = games.screen.height/2
self.dy = 0
self.dx = 0
# moves the ball if mouse is pressed
if games.mouse.is_pressed(1):
self.dx = -3
I'm making a Pong clone for learning purposes, and need to get the ball moving from the middle of the screen (it's sent there when it goes past a paddle) when the mouse is pressed. I've tried the following code, but it does nothing, so I probably don't understand the syntax. Try to keep it as simple as possible please, and explain it, I'd rather not have 50 lines of code for this (I want to understand everything I'm using here). I think this is all the relevant code, sorry if it isn't. Thanks.
def middle(self):
"""Restart the ball in the centre, waiting for mouse click. """
# puts ball stationary in the middle of the screen
self.x = games.screen.width/2
self.y = games.screen.height/2
self.dy = 0
self.dx = 0
# moves the ball if mouse is pressed
if games.mouse.is_pressed(1):
self.dx = -3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据该代码片段不可能确切知道发生了什么,但看起来您使用了错误的函数来检测鼠标按钮是否被按下。
games 模块中的
Screen.is_pressed
包装了pygame.key.get_pressed
,它仅检测键盘按键的状态,而不检测鼠标按钮的状态。您可能需要函数Screen.mouse_buttons
,它包装pygame.mouse.get_pressed
。您可以在这样的循环中使用它(我假设您有一个名为“screen”的games.Screen
实例):It's impossible to know exactly what's happening based on that code fragment, but it looks like you are using the wrong function to detect whether or not the mouse button is pressed.
Screen.is_pressed
from the games module wrapspygame.key.get_pressed
, which only detects the state of keyboard keys, not mouse buttons. You probably want the functionScreen.mouse_buttons
, which wrapspygame.mouse.get_pressed
. You could use it within a loop like this (I'll pretend you have an instance ofgames.Screen
called 'screen'):我正在寻找与初学者
Python
编码器相同的问题 -Games.py
(修订版 1.7)在各种类中包含多个is_pressed
方法,包括键盘和鼠标。由于 pygame 是一个编译模块(我有 1.9.1),引用文档而不是源代码,我发现 这里有一个 pygame.mouse.get_pressed():
将获取鼠标按钮的状态
所以我认为问题是在我们的代码中使用这个而不是使用错误的函数......
好的得到这个工作 - 我的修复:
调用Main() 使选定的精灵移动到鼠标位置。华泰
I am looking at the same issue as a beginner
Python
coder -Games.py
(revision 1.7) includes severalis_pressed
methods in various classes, including both keyboard and mouse.since pygame is a compiled module (I have 1.9.1) referring to the documentation rather than source code, I find here that there is a pygame.mouse.get_pressed():
the will get the state of the mouse buttons
So I think the issue is the use of this in (y)our code rather than the use of the wrong function.....
OK GOT THIS TO WORK - MY FIX:
invoking the in Main() causes the selected sprite to move to the mouse location. HTH