Pygame开发谷歌恐龙类游戏:解决'function'对象不可迭代错误
错误原因与修复方案
核心问题
你定义的cacti函数最后错误地返回了函数本身(return cacti),而非函数内部创建的仙人掌列表list_of_cacti。这导致list_of_cacti = cacti(5, ground_surf_rect)执行后,list_of_cacti是一个函数对象,不是可迭代的列表,所以在for cactus in list_of_cacti循环时触发TypeError: 'function' object is not iterable错误。
修复步骤
1. 修正cacti函数的返回值
将函数末尾的return cacti改为return list_of_cacti,让函数返回生成好的仙人掌列表:
def cacti(number, ground_surf_rect): list_of_cacti = [] start_x_coord = ground_surf_rect.width / 2 # start at the middle of the screen for i in range(number): current_cactus = {} # prepare empty dictionary to package surf and rect x_coord = start_x_coord + random.randint(200, 400) # make the next cactus between 200 and 400 cactus_surf, cactus_surf_rect = one_cactus(ground_surf_rect) cactus_surf_rect.left = x_coord # adjust the x coordinate to the random one # now package the surface the the rect coordinates into one dictionary current_cactus['surf'] = cactus_surf current_cactus['rect'] = cactus_surf_rect # add the dictionary containing info about one cactus into a list list_of_cacti.append(current_cactus) start_x_coord = x_coord # reset the start x coordinate to that of the latest cactus return list_of_cacti # 修改为返回生成的仙人掌列表
2. 可选清理冗余代码
主程序中你单独创建了一个cactus_surf, cactus_surf_rect,并在循环外绘制它,这会导致屏幕上同时出现手动创建的单个仙人掌和列表中的多个仙人掌。如果不需要这个单独的仙人掌,可以删除以下两行代码:
cactus_surf, cactus_surf_rect = one_cactus(ground_surf_rect)
display_surf.blit(cactus_surf,cactus_surf_rect)
验证效果
修改后运行代码,list_of_cacti会变成包含5个仙人掌字典的可迭代列表,循环遍历操作将正常执行,仙人掌会按预期向左移动并显示在屏幕上。
内容的提问来源于stack exchange,提问作者MYW
相关产品推荐
相关产品推荐

