开发者

Moving a sprite when mouse is pressed in Python

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 simp开发者_运维问答le 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


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 wraps pygame.key.get_pressed, which only detects the state of keyboard keys, not mouse buttons. You probably want the function Screen.mouse_buttons, which wraps pygame.mouse.get_pressed. You could use it within a loop like this (I'll pretend you have an instance of games.Screen called 'screen'):

left, middle, right = screen.mouse_buttons()
# value will be True if button is pressed
if left:
    self.dx = -3


I am looking at the same issue as a beginner Python coder - Games.py (revision 1.7) includes several is_pressed methods in various classes, including both keyboard and mouse.

class Mouse(object):

#other stuff then 
def is_pressed(self, button_number):
    return pygame.mouse.get_pressed()[button_number] == 1

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

get_pressed() -> (button1, button2, button3)

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:

class myClass(games.Sprite):
    def update(self):
        if games.mouse.is_pressed(0)==1:
            self.x=games.mouse.x
            self.y=games.mouse.y

invoking the in Main() causes the selected sprite to move to the mouse location. HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜