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

Pygame沙盒程序报错排查:'str'对象无'update'属性问题

问题原因与解决方法

错误根源

你遇到的AttributeError是因为遍历字典sand时,默认迭代的是字典的键(这里是字符串类型的sand_id),而不是Grain类的实例对象。字符串没有update()方法,所以调用grain.update()会触发错误。

修复代码

将出错的循环:

for grain in sand:
    grain.update()

修改为遍历字典的值(即Grain实例):

for grain in sand.values():
    grain.update()

额外优化提示

当前代码中事件处理逻辑放在了沙粒更新之后,建议将事件处理移到主循环开头,这样输入响应会更及时,调整后的主循环结构示例:

while not is_crashed:
    # 优先处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_crashed = True
        # ... 其余鼠标事件处理代码 ...
    
    # 处理鼠标按住生成沙粒
    mouse_x, mouse_y = pygame.mouse.get_pos()
    mouse_held = pygame.mouse.get_pressed()[0]
    if mouse_held:
        sand[str(sand_id)] = Grain(mouse_x, mouse_y)
        sand_id += 1
    
    # 更新沙粒状态
    for grain in sand.values():
        grain.update()
    
    # 绘制与画面刷新
    game_display.fill(WHITE)
    for grain in sand.values():
        grain.draw(game_display, sand_grain)
    pygame.display.flip()
    clock.tick(FPS)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:38:09