检测鼠标点击每一个精灵或对象在一个组



我是一个使用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

中的组中被点击

遍历pygame.sprite.Grouppygame.sprite.Sprite对象,并使用pygame.Rect.collidepoint:

测试鼠标位置是否位于精灵的区域(.rect属性)。
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}")

最新更新