我正在为班级的最后一个项目制作游戏,由于某种原因,当我在列表中时,我无法检查rect对象的click事件。如果我使用for循环遍历Opened_Pack列表并尝试单击它,那么什么也不会发生(这是我在下面的代码)。当我使用索引([0],[1]等)进行尝试时,无论我使用多少数字或列表有多大,都会出现索引超出范围错误。所以我想我的问题是:有没有一种方法可以检查是否单击了rect数据是否存储在列表中?我敢肯定,必须存在,但我无法弄清楚。
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
答案 0 :(得分:3)
代码的迭代长度为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 ) )
编辑:添加了一堆调试代码
答案 1 :(得分:0)
这两个列表都是在主while循环内创建的,因此,很显然,游戏更新的每一帧都会重新创建列表。我只是将它们移到主循环之外,现在效果很好。