renpytom / rapt-pygame-example

Example of using RAPT to package Pygame(_sdl2) games.
231 stars 39 forks source link

App crashing when pygame.mouse.get_pressed() is triggered #17

Open umbe1987 opened 6 years ago

umbe1987 commented 6 years ago

I made a game which uses pygame.mouse.get_pressed() to check whether the mouse left button is pressed. The complete code is in my repo. If this happens, it checks whether the position of the click is LEFT RIGH UP or DOWN of a joypad draw. This moves a character towards the correct direction. The game works when I test it on my Ubuntu machine, but it crashes as soon as I touch whatever area of the screen on mobile (no matter if it's within the joypad's buttons or outside). I check for mouse left with the code below inside a Joypad class:

    def btn_pressed(self, mouse_event):

        # check if left mouse is being pressed
        if pygame.mouse.get_pressed()[0]:
            x, y  = mouse_event.pos
            if self.btn_up.rect.collidepoint(x, y):
                return 'UP'
            elif self.btn_down.rect.collidepoint(x, y):
                return 'DOWN'
            elif self.btn_left.rect.collidepoint(x, y):
                return 'LEFT'
            elif self.btn_right.rect.collidepoint(x, y):
                return 'RIGHT'

Then, in the Character class I do:

    def move(self, joypad_direction):
        """
        move the character
        to be used along with Joypad.btn_pressed returns
        ('UP', 'DOWN' 'LEFT', 'RIGHT')
        """

        self.dx = 0
        self.dy = 0

        # check for horizontal move
        if joypad_direction == 'LEFT':
            self.dx = -self.speed
            self.rect.move_ip(-self.speed, 0)
        if joypad_direction == 'RIGHT':
            self.dx = +self.speed
            self.rect.move_ip(self.speed, 0)

        self.dx = 0

        # check for vertical move
        if joypad_direction == 'UP':
            self.dy = -self.speed
            self.rect.move_ip(0, -self.speed)
        if joypad_direction == 'DOWN':
            self.dy = +self.speed
            self.rect.move_ip(0, self.speed)
        self.dy = 0

Finally, in my main function I do:

    while True:

        ev = pygame.event.wait()

        # If not sleeping, draw the screen.
        if not sleeping:
            hero.move(joypad.btn_pressed(ev))
            screen.fill((0, 0, 0, 255))

            joypad.buttons.draw(screen)

            if x is not None:
                screen.blit(hero.image, (x, y))

            pygame.display.flip()
umbe1987 commented 6 years ago

Maybe pygame_sdl2 is a better repo to talk about this issue. Will cpoy this there too.