python - Pygame pop() 类崩溃
问题描述
在我尝试使用 pygame 制作的游戏中,我的玩家能够射击从数组中的类的实例创建的“子弹”(名为“shots”),但是当我尝试删除它们时,程序会崩溃。下面是我的代码,我做错了什么导致它崩溃?
for i in range(len(shots)):
shots[i].shoot()
shots[i].drawBullet()
if shots[i].x > swidth or shots[i].x < 0:
shots.pop(i)
解决方案
问题是,您在删除 ( pop
) 项时遍历列表。当您删除列表的最后一项时,该项目的索引仍包含在 rangerange(len(shots))
中,但访问shots[i]
将失败。
一个简单的解决方法是以相反的顺序遍历列表。反转范围reversed
:
for i in reversed(range(len(shots))):
shots[i].shoot()
shots[i].drawBullet()
if shots[i].x > swidth or shots[i].x < 0:
shots.pop(i)
另一种选择是迭代列表的浅表副本([:])并从原始列表中删除元素。请参阅数据结构:
for shot in shots[:]:
shot.shoot()
shot.drawBullet()
if shot.x > swidth or shot.x < 0:
shots.remove(shot)
推荐阅读
- html - ios 的 slick 解决方法
- python - 如何使用 z3py 设置“最多 n 次”等要求?
- python - 使用pyaudio的回调模式使用pydub播放音频时出现问题
- php - 如何在 php 文件中包含静态资源,如图像、css 和 javascript
- sql - 针对 dbms 问题改进 sql 查询
- firebase - Firebase 事件发生时更新反应原生(博览会)UI
- python - 如何仅打印此输出的最后一行?
- r - 使用 read_html 在 R 中读取时处理 404 和其他错误 URL
- excel - 在 Excel VBA 中删除条件
- python - 在 sqlalchemy 中插入父对象时插入子对象列表