Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

pygame - How to detect touch screen clicks in python?

How can I detect if an image has been touched in pygame on a touch screen? I have searched but I can not find how to detect if a particular image is touched.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To detect if an image has been touched, you can use the MOUSEBUTTONDOWN event. See Pygame mouse clicking detection.

Load the image with pygame.image.load(). Crate the bounding rectangle (pygame.Rect). Create a pygame.Mask from the image with pygame.mask.from_surface:

image = pygame.image.load('image.png').convert_alpha()
image _rect = image.get_rect(topleft = (x, y))
image_mask = pygame.mask.from_surface(image)

Use the MOUSEBUTTONDOWN event to detect if the mouse is clicked in the rectangular area of the image. Check if the corresponding bit in the image mask is set:

for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONDOWN:
        image_x, image_y = event.pos[0] - image_rect.x, event.pos[1] - image_rect.y
        if image_rect.collidepoint(event.pos) and image_mask.get_at((image_x, image_y)):
            print("touched")

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Text", True, (255, 255, 0))

bomb = pygame.image.load('Bomb-256.png').convert_alpha()
bomb_rect = bomb.get_rect(center = window.get_rect().center)
bomb_mask = pygame.mask.from_surface(bomb)
click_count = 0
click_text = font.render('touch: ' + str(click_count), True, "black")

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 
        if event.type == pygame.MOUSEBUTTONDOWN:
            image_x, image_y = event.pos[0] - bomb_rect.x, event.pos[1] - bomb_rect.y
            if bomb_rect.collidepoint(event.pos) and bomb_mask.get_at((image_x, image_y)):
                click_count += 1
                click_text = font.render('touch: ' + str(click_count), True, "black")

    window.fill((255, 255, 255))
    window.blit(bomb, bomb_rect)
    window.blit(click_text, click_text.get_rect(topleft = (20, 20)))
    pygame.display.flip()

pygame.quit()
exit()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...