gpt4 book ai didi

python - 有没有办法在给定 Rect 对象列表的情况下检查 MOUSBUTTONDOWN 事件?

转载 作者:行者123 更新时间:2023-12-01 15:44:57 24 4
gpt4 key购买 nike

我正在为我的类(class)期末项目制作游戏,但出于某种原因,我无法检查列表中矩形对象上的点击事件。如果我使用 for 循环遍历 Opened_Pack 列表并尝试单击它,则什么也不会发生(这是我下面的代码)。当我尝试使用索引([0]、[1] 等)时,无论我使用什么数字或列表有多大,都会出现索引超出范围错误。所以我想我的问题是:如果数据存储在列表中,有没有办法检查我是否单击了矩形?肯定有,但我想不通。

Opened_Pack = []
Pack_Card_Recs = []

for event in pygame.event.get():
mouse = pygame.mouse.get_pos()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
window = pygame.display.set_mode((850,850), pygame.RESIZABLE)
#Key Bindings to open Packs, WILL BE REPLACED WITH CLICKS (eventually)
if event.key == pygame.K_r:
Opened_Pack = TwoPlayerPack.Open()
Pack_Card_Recs = [Opened_Pack[i].getRect() for i in range(len(Opened_Pack))]
#print(Pack_Card_Recs[0])
elif event.key == pygame.K_e:
Opened_Pack= SixPlayerPack.Open()
Pack_Card_Recs = [Opened_Pack[i].getRect() for i in range(len(Opened_Pack))]
elif event.key == pygame.K_t:
Opened_Pack = SevenPlayerPack.Open()
Pack_Card_Recs = [Opened_Pack[i].getRect() for i in range(len(Opened_Pack))]
elif event.key == pygame.K_u:
Opened_Pack= FourPlayerPack.Open()
Pack_Card_Recs = [Opened_Pack[i].getRect() for i in range(len(Opened_Pack))]

if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
for i in range(len(Opened_Pack)):
if Pack_Card_Recs[i].collidepoint(x,y):
print("Clicked Player at index: " + str(i))

if event.type == pygame.QUIT:
run = False

最佳答案

代码迭代 Opened_Pack 的长度,而所讨论的矩形存储在列表 Pack_Card_Recs 中。只需修改循环范围即可解决此问题。

if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
print( "%d rectangles to check" % ( len( Pack_Card_Recs ) ) )
for i in range( len( Pack_Card_Recs ) ): # <-- HERE, not Opened_Pack
r = Pack_Card_Recs[i]
print( "Is point (%d, %d) inside Rect #%d [%d, %d, %d x %d]" % ( x, y, i, r.x, r.y, r.width, r.height ) )
if r.collidepoint( x,y ):
print( "Clicked Player at index: " + str( i ) )

编辑:添加了一堆调试代码

关于python - 有没有办法在给定 Rect 对象列表的情况下检查 MOUSBUTTONDOWN 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com