首页 > 解决方案 > 检测组中每个精灵或对象的鼠标点击

问题描述

我是使用随机颜色制作颜色网格pygame.Color(random.choice(color_list)),将所有立方体放在一个组中,这样我就可以了<GROUPNAME>.draw(screen),但我想检测是否在组中单击了精灵,这是我的代码:

import pygame
import sys
import os
import time
from asset import CreateAsset

pygame.init()
screen_size = screen_width, screen_height = 508, 436
screen = pygame.display.set_mode(screen_size)
running = True
count = 0
cubes = pygame.sprite.Group()
pox = 5
poy = 5
for i in range(19):
    for i in range(14):
        time.sleep(0.1)
        cubex = CreateAsset(pox, poy, 30)
        pox += 36
        cubes.add(cubex)
        count += 1
    pox -= pox
    pox += 5
    poy += 3

while running:

    screen.fill(pygame.Color("Black"))
    cubes.draw(screen)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    pygame.display.flip()
pygame.quit()
sys.exit()

“资产”来自另一个文件,它制作立方体,poy 和 pox 是盒子的 xy 位置。 问题:如何检测是否在pygame中的组中单击了精灵

标签: pythonpygame

解决方案


遍历对象并测试鼠标位置是否在Spritepygame.sprite.Group的区域(属性)中:pygame.sprite.Sprite.rectpygame.Rect.collidepoint

while running:

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            cube_list = cubes.sprites()
            for i, cubex in enumerate(cube_list):
                if cubex.rect.collidepoint(event.pos):
                    print(f"clicked: {i}")

推荐阅读