You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyGame接苹果游戏苹果闪烁问题技术求助

解决多苹果场景下的下落闪烁问题

问题根源

闪烁的核心原因是遍历苹果列表时同时执行删除操作,导致enumerate生成的索引和实际列表长度不同步。当多个苹果存在时,删除某个元素后,后续元素的索引会前移,但遍历仍按原索引进行,直接跳过了部分苹果的绘制,出现“消失-出现”的闪烁现象。

修复方案

  1. 移除多余的index变量,添加苹果直接用append(),无需手动维护索引
  2. 改用反向遍历列表,避免删除操作影响后续元素的遍历
  3. 优化碰撞判断的代码结构,提升可读性

修改后的关键代码

# 初始化时移除index变量,直接添加第一个苹果
apples = []
appleImg = pygame.image.load("images/apple.png")
appleImg = pygame.transform.scale(appleImg, (appleSize, appleSize))
apples.append([random.randint(0,WIDTH-appleSize),50])

def game(dt):
    global last_apple
    # 移除index变量,添加苹果用append
    if(time.time() - last_apple >= 0.7):
        last_apple = time.time()
        apples.append([random.randint(0,WIDTH-appleSize),50])
    pressedKeys = pygame.key.get_pressed()
    if (pressedKeys[pygame.K_a]):
        catch.moveLeft(velocity * dt)
    if (pressedKeys[pygame.K_d]):
        catch.moveRight(velocity * dt)
    if (pressedKeys[pygame.K_w]):
        apples.append([random.randint(0,WIDTH-appleSize),50])

    # 反向遍历苹果列表,避免删除元素导致的索引混乱
    for i in range(len(apples)-1, -1, -1):
        x, y = apples[i]
        value = (velocity - 1000) * dt
        new_y = y + value
        apples[i][1] = new_y
        
        # 创建苹果碰撞矩形
        apple_rect = pygame.Rect(x, new_y, appleSize, appleSize)
        catch_rect = pygame.Rect(catch.x, catch.y+5, catch.w, catch.h)
        col = apple_rect.colliderect(catch_rect)
        
        # 绘制苹果
        screen.blit(appleImg, (x, new_y))
        
        # 判断是否移除苹果
        if (col and new_y + appleSize <= catch.y + 30) or (new_y + appleSize >= catch.height):
            apples.pop(i)

    catch.draw()
    pygame.draw.rect(screen,(30,30,30),pygame.Rect(0,HEIGHT-75,WIDTH,75))

额外优化建议

  • 尽量避免在游戏循环中使用time.time(),改用Pygame内置的pygame.time.get_ticks(),精度更高且更适配游戏循环
  • 将苹果的位置存储为pygame.Rect对象,减少重复创建Rect的开销,代码更简洁

内容的提问来源于stack exchange,提问作者Marci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:17:45