python - 检测组中每个精灵或对象的鼠标点击
问题描述
我是使用随机颜色制作颜色网格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中的组中单击了精灵
解决方案
遍历对象并测试鼠标位置是否在Spritepygame.sprite.Group
的区域(属性)中:pygame.sprite.Sprite
.rect
pygame.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}")
推荐阅读
- c# - 未找到 Http Post 500 错误
- java - 如何检查 Firebase Firestore 事务是否已更新到服务器?
- dart - AppBar 中的字幕
- php - 当我使用 Laravel JWT 时,这条线出现在路由类中,但我无法确定错误
- javascript - 如何将数据传递给另一个视图 laravel
- priority-web-sdk - 发布自定义优先级字段时出现 REST API 错误
- java - 语法错误(代码 1):,编译时:INSERT INTO rest_tables(0,TABLENUMBER) VALUES (?,?)
- c++ - 无锁原子在实践中是无地址的吗?
- c - C -(malloc、calloc 或静态)从函数返回的 2d 字符数组
- excel-formula - 如何更正 Excel 公式错误