roni280
roni280

Reputation: 67

pygame don't recognize the correct rect of my image

at Pygame I have a game with a background(at the code the image named:'bg) and an image on that(named:'dice') I'm trying to notice when the player is clicking at the image, but it writing me that the rect of the dice is 0,0(x=0 and y=0), while the image is shown at 740,40.

what should I do?

bg = pygame.image.load("temptry.gif")
dice=pygame.image.load("dicee.gif")
screen.blit(bg, (0, 0))
bg.blit(dice,(740,40))
pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            print dice.get_rect()
            if dice.get_rect().collidepoint(x, y):
                print "omg"
    screen.blit(bg, (0, 0))
    bg.blit(dice,(740,40))
    pygame.display.update()

Upvotes: 2

Views: 271

Answers (1)

abc1234
abc1234

Reputation: 260

There are multiple problems in your code. Before the main loop you do not need pygame.display.update(). Next you should .convert() your images. For example dice = pygame.image.load("dicee.gif").convert() . Also there may be a problem with loading GIFS.

It seems like you are using very complicated ways of doing things. What I would suggest is that you have all the images loaded behind your main loop, convert the. After the main loop blit the image. Instead of doing bg.blit(dice,(740,40)) how about you just do screen.blit(bg,(740,40))

Next you should make a mouse position variable after the main loop.

It should look like this

mouse_pos = pygame.mouse.get_pos()

Next you should create rects for your dice image. Set a variable for it

dice_rect = dice.get_rect()

Then make an if statement that tests if someone clicks on the dice image

if pygame.mouse.get_pressed()[0] and dice_rect.collidepoint(mouse_pos):
      print "omg"

Then do pygame.display.update()

I hope this helped, if you have any further questions about this comment below.

Upvotes: 1

Related Questions