首页 > 解决方案 > 单击发射子弹时出现递归错误

问题描述

我正在编写一个目标射击游戏,最近开始使用“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

我认为这是将我的一个函数转换为迭代循环而不是递归循环的情况,但我不知道如何做到这一点。非常感谢任何帮助。

标签: python

解决方案


您应该在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)

推荐阅读