python - 单击发射子弹时出现递归错误
问题描述
我正在编写一个目标射击游戏,最近开始使用“pygame.sprite”。我目前正在编程子弹功能以向光标射击。理想情况下,我想为此使用 pygame.sprite 来利用内置的碰撞系统。我曾尝试重用我制作的另一个程序的代码并将其转换为两个函数,如下所示:
def bullet_maker():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
dx = event.pos[0] - (player_sprite.rect.x + player_sprite.rect.w // 2 )
dy = event.pos[1] - player_sprite.rect.y
direction = pygame.math.Vector2(dx, dy).normalize()
bullet = {'x': player_sprite.rect.x + 42, 'y': player_sprite.rect.y, 'direction': direction}
all_bullets.append(bullet)
def bullet_movement():
for item in all_bullets:
item['x'] += item['direction'][0]
item['y'] += item['direction'][1]
if 0 < item['x'] < 800 and 0 < item['y'] < 575:
bullet_sprites.add(item)
我的子弹精灵类如下所示:
bullet_img = pygame.image.load('bullet.png')
class Bullet(pygame.sprite.Sprite):
def __init__(self, width, height):
pygame.sprite.Sprite.__init__(self, bullet_sprites)
self.image = pygame.Surface([width, height])
self.image = bullet_img
self.rect = self.image.get_rect()
self.rect.center = (400,400)
bullet_sprites = pygame.sprite.Group()
all_bullets = []
最后,我的绘图功能如下图所示:
def refresh_window():
window.blit(bgr, (0,0))
player_sprites.draw(window)
target_sprites.draw(window)
for item in bullet_sprites:
Bullet.image.draw(window)
pygame.display.update()
一切运行良好,但是当我单击屏幕发射子弹时,游戏崩溃并出现以下错误:
Traceback (most recent call last):
File "main.py", line 123, in <module>
bullet_movement()
File "main.py", line 88, in bullet_movement
bullet_sprites.add(item)
File "/usr/local/lib/python3.6/dist-packages/pygame/sprite.py", line 366, in add
self.add(*sprite)
File "/usr/local/lib/python3.6/dist-packages/pygame/sprite.py", line 366, in add
self.add(*sprite)
File "/usr/local/lib/python3.6/dist-packages/pygame/sprite.py", line 366, in add
self.add(*sprite)
[Previous line repeated 330 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
我认为这是将我的一个函数转换为迭代循环而不是递归循环的情况,但我不知道如何做到这一点。非常感谢任何帮助。
解决方案
您应该在bullet_movement函数的开头为bullet_stripes添加一个全局声明:
def bullet_movement():
global bullet_sprites
for item in all_bullets:
item['x'] += item['direction'][0]
item['y'] += item['direction'][1]
if 0 < item['x'] < 800 and 0 < item['y'] < 575:
bullet_sprites.add(item)
推荐阅读
- google-cloud-functions - 如何使用谷歌云构建在一个源存储库中为多个谷歌云功能实施 CI/CD?
- amazon-ec2 - 如何将 AWS EC2 安全组中的 Atlassian/Bitbucket IP 列入白名单?
- javascript - 根据 ajax 返回的数据渲染 Html 选择列表
- javascript - 散景仪表板:有什么方法可以保存用户选择以重新加载页面?
- python - 从元组列表中获取具有“NaN”的元组索引
- android - Recyclerview 没有在 android 中更新
- pip - LinAlgError:不是正定的,即使有抖动。使用 conda 环境而不是 pip 时
- assembly - 如何在 Emu8086 汇编语言中显示用户的输入
- javascript - 将数据从html表导出到csv文件时如何删除列?
- python-3.x - 根据条件计算 pandas 数据框中的 sumproduct(Excel)